Coder Perfect

How to: Run a command line in C# and obtain STD OUT output


How can I use C# to run a command-line program and receive the STD OUT output? I want to run DIFF on two files that I’ve selected programmatically and publish the results to a text field.

Asked by Wing

Solution #1

// 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 = "YOURBATCHFILE.bat";
 // 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();

The code was taken from MSDN.

Answered by Ray Jezek

Solution #2

As an example, consider the following:

//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;

//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;

pProcess.StartInfo.UseShellExecute = false;

//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;   

pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;

//Start the process

//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();

//Wait for process to finish

Answered by Jeremy

Solution #3

I discovered another handy argument, which I use to remove the process window.

pProcess.StartInfo.CreateNoWindow = true;

If you want to entirely hide the black console window from the user, this will assist.

Answered by Peter Du

Solution #4

// usage
const string ToolFileName = "example.exe";
string output = RunExternalExe(ToolFileName);

public string RunExternalExe(string filename, string arguments = null)
    var process = new Process();

    process.StartInfo.FileName = filename;
    if (!string.IsNullOrEmpty(arguments))
        process.StartInfo.Arguments = arguments;

    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;

    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    var stdOutput = new StringBuilder();
    process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.

    string stdError = null;
        stdError = process.StandardError.ReadToEnd();
    catch (Exception e)
        throw new Exception("OS error while executing " + Format(filename, arguments)+ ": " + e.Message, e);

    if (process.ExitCode == 0)
        return stdOutput.ToString();
        var message = new StringBuilder();

        if (!string.IsNullOrEmpty(stdError))

        if (stdOutput.Length != 0)
            message.AppendLine("Std output:");

        throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message);

private string Format(string filename, string arguments)
    return "'" + filename + 
        ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) +

Answered by Lu55

Solution #5

The accepted answer on this page has a flaw that can be problematic in rare circumstances. By convention, stdout and stderr are the two file handles to which programs write. If you only read a single file handle, such as Ray’s response, and the program you’re beginning writes enough output to stderr, the output stderr buffer will fill up and the program will crash. Then your two processes are stuck in a loop. It’s possible that the buffer will be 4K in size. This is exceedingly rare in short-lived programs, but it will happen eventually if you have a long-running program that outputs to stderr repeatedly. It’s difficult to trace down and debug this.

There are a few viable options for dealing with this.

Answered by Cameron

Post is based on