6

How execute command via shell and return the complete output as a string using C#?

equivalent to shell_exec() of PHP.

Thanks,advanced.

The Mask
  • 17,007
  • 37
  • 111
  • 185

3 Answers3

5

Use the Process class

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
5

The MSDN documentation on Process.StandardOutput documentation shows an example

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

You might like to extract the standard error stream as well.

1

Look at the Process class Standard Output and Standard Error, and the OutputDataReceived and ErrorDataReceived recieved events.

There is a CodeProject article here, which you may find helpful.

RichardOD
  • 28,883
  • 9
  • 61
  • 81