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);
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s