Redirecting standard output using Process

If we are running a console application, we might wish to capture the output for our own use…

Asynchronous output

By default any “standard” output from an application run via the Process class, is output to it’s own window. To capture this output for our own use we can write the following…

using (var p = new Process())
{
   p.StartInfo = new ProcessStartInfo("nant", "build")
   {
      UseShellExecute = false,
      RedirectStandardOutput = true
   };

   p.OutputDataReceived += OnOutputDataReceived;
   p.Start();
   p.BeginOutputReadLine();
   p.WaitForExit();
   return p.ExitCode;
}

The above is part of a method that returns an int and runs nant with the argument build. I wanted to capture the output from this process and direct to my own console window.

The bits to worry about are…

  1. Set UseShellExecute to false
  2. Set RedirectStandardOutput to true
  3. Subscribe to the OutputDataReceived event
  4. Call BeginOutputReadLine after you start the process

Synchronous output

If you want to do a similar thing but capture all the output when the process ends, you can use

using (var p = new Process())
{
   p.StartInfo = new ProcessStartInfo("nant", "build")
   {
      UseShellExecute = false,
      RedirectStandardOutput = true
   };

   p.Start();
   p.WaitForExit();

   using (StreamReader reader = p.StandardOutput)
   {
      Console.WriteLine(reader.ReadToEnd());
   }
   return p.ExitCode;
}

In this synchronous version we do not output anything until the process completes, then we read for the process’s StandardardOutput. We still require UserShellExecute and RedirectStandardOutput to be setup as previously outlined, but no longer subscribe to any events or use BeginOutputReadLine to start the output process.