2

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

5
  • What commands do you mean? Something like ping, copy, calc, notepad etc? Commented Mar 4, 2015 at 22:59
  • @JamesBlond Any command in general Commented Mar 4, 2015 at 22:59
  • Ok, then just have a look at the duplicate link from Ken White. The chosen answer contains everything you need. Commented Mar 4, 2015 at 23:42
  • Have a look here: stackoverflow.com/questions/1469764/run-command-prompt-commands Commented Mar 4, 2015 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. Commented Mar 5, 2015 at 0:47

1 Answer 1

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:\\");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.