Redirecting the StandardInput, StandardError(stderr) and the StandarOutput Using the Process Class

Short Description

This example has as its main goal to illustrate one of the many possibilities that we have while using the Process class.

Article

I can lunch any program from a C# applicationusing the Process class. But what if I want to redirect theStandarInput(the keyboard), the StandardError(stderr) and theStandarOutput (the video)? Well, this can be achieved easily with theprocess class. First of all we need to instantiate a ProcessStartInfoclass passing as constructor param the name of the app that we want tolunch and to set some parameters to be passed to the Process instances(p):

ProcessStartInfo psI = new ProcessStartInfo("cmd");

The property psI.UseShellExecute was set as false, to be able to redirect the StandardInput, etc. After the properties

psI.RedirectStandardInput
psI.RedirectStandardOutput
psI.RedirectStandardError

…are set to true.

To avoid the cmd annoying window we set astrue the property psI.CreateNoWindow so no window will be created forthe cmd app.Finally we set the p.StartInfo property to the instance ofProcessStartInfo that we have just created and voila , start theprocess.

To be able to capture the p.StandardInput,p.StandardOutput and p.StandardError we get the File Descriptors(StreamReaders and StreamWriter classes) to read the StandardOutput andStandardError and to write to the StandardInput. The read and writeoperations are performed as we do it in a normal file. (Hmm, does thisway of working with the IO remind you the unix world?) The process cmdis closed when we close the p.StandardInput file descriptor.

At the very end we read the p.StandardOutputand p.StandardError file descriptors into the text box. See thecomplete code of the method that implements the whole stuff.

private void start()
{
Process p = new Process();
StreamWriter sw;
StreamReader sr;
StreamReader err;

ProcessStartInfo psI = new ProcessStartInfo("cmd");
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
psI.RedirectStandardError = true;
psI.CreateNoWindow = true;
p.StartInfo = psI;

p.Start();
sw = p.StandardInput;
sr = p.StandardOutput;
err = p.StandardError;

sw.AutoFlush = true;
if (tbComm.Text != "")
sw.WriteLine(tbComm.Text);
else
//execute default command
sw.WriteLine("dir \");

sw.Close();

textBox1.Text = sr.ReadToEnd();
textBox1.Text += err.ReadToEnd();
}

Download process.zip

————————-

Edwin Lima is a software engineer working forNEC Computers International BV in the Netherlands. Most of his timehe's busy with data integration tasks and in his free time he playsaround with C# and .NET related stuff (contact me at:edwinlima@hotmail.com)

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!