Redirecting Output and Error Streams

This is the code needed to capture both the output and error streams from a console mode application.

using System;
using System.Text;
using System.Diagnostics;

namespace RedirectOutput
{
class Program
{
static StringBuilder errorBufffer = new StringBuilder();
static StringBuilder outputBufffer = new StringBuilder();

static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.FileName = “cmd.exe”;
psi.Arguments = “/C dir”;
psi.WorkingDirectory = @”c:photos”;
using (Process p = new Process())
{
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.OutputDataReceived += p_OutputDataReceived;
p.ErrorDataReceived += p_ErrorDataReceived;

p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
Console.WriteLine(“Error”);
Console.WriteLine(errorBufffer.ToString());
Console.WriteLine(“Output”);
Console.WriteLine(outputBufffer.ToString());

Console.ReadLine();
}

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
outputBufffer.AppendLine(e.Data);
}

static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
errorBufffer.AppendLine(e.Data);
}
}
}