2

Is it possible for me to call Windows commands, like in the command prompt, from windows forms with C sharp? If so, how?

Jetscooters
  • 123
  • 2

1 Answers1

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