Pages

Friday, April 5, 2013

Redirection of the Input/Output for processes

It is very comfortable to have redirected input and output for your console processes. For example, lets imagine a situation when you have to start scripts from your application (it might be something like script manager). So you have a collection of running processes and in order to handle them properly you have to start them with different arguments, get their messages, handle (or log) their exceprions.
Fortunately there is an easy way to achieve it. We can use RedirectStandartOutput, RedirectStandartInput and RedirectStandartError properties of the ProcessStartInfo class.
First of all we have to set those properties to true, then we have to set UseShellExecute propertie to false (because it allows us to redirect streams) and, finally, process different events. And do not forget to start listening to those streams!
Here is a simple example to run vbs script in a hidden way:

System.Diagnostics.Process p = new System.Diagnostics.Process();

p.StartInfo = new System.Diagnostics.ProcessStartInfo("cscript");
p.StartInfo.Arguments = "C:\\test.vbs";

p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;

p.OutputDataReceived += (proc, outLine) => LogMessage(outLine.Data);
p.ErrorDataReceived += (proc, outLine) => LogError(outLine.Data);

p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine ();