Is it possible for me to call Windows commands, like in the command prompt, from windows forms with C sharp? If so, how?
Asked
Active
Viewed 497 times
2
-
What commands do you mean? Something like ping, copy, calc, notepad etc? – Chief Wiggum Mar 04 '15 at 22:59
-
@JamesBlond Any command in general – Jetscooters Mar 04 '15 at 22:59
-
Ok, then just have a look at the duplicate link from Ken White. The chosen answer contains everything you need. – Chief Wiggum Mar 04 '15 at 23:42
-
Have a look here: http://stackoverflow.com/questions/1469764/run-command-prompt-commands – Smudge Mar 04 '15 at 23:55
-
Try Process.Start(). If you are providing a string path to a file, then the file will be opened by the default application. – iCode Mar 05 '15 at 00:47
1 Answers
4
The simplest way is to do the following as shown here..
Process.Start("Executable name here", "parameters here");
However, if you want to set a working directory, capture standard output or errors, create no window etc. You could do something like the following..
void StartNewProcess(string processName, string parameters, string startDir)
{
var proc = new Process();
var args = new ProcessStartInfo
{
FileName = processName,
Arguments = parameters,
WorkingDirectory = startDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
proc = Process.Start(args);
proc.ErrorDataReceived += p_DataReceived;
proc.OutputDataReceived += p_DataReceived;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
And then you can process the output using something like this..
void p_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null && e.Data.Length > 0) Console.WriteLine(e.Data);
}
Example to call..
void button1_Click(object sender, EventArgs e)
{
//Input params: Executable name, parameters, start directory
StartNewProcess("cmd.exe", "/C dir", "C:\\");
}

Magic Mick
- 1,475
- 1
- 21
- 32