Redirect the output (stdout, stderr) of a child process to the Output window in Visual Studio

Andrew Russell picture Andrew Russell · Sep 4, 2010 · Viewed 17.5k times · Source

At the moment I am starting a batch file from my C# program with:

System.Diagnostics.Process.Start(@"DoSomeStuff.bat");

What I would like to be able to do is redirect the output (stdout and stderr) of that child process to the Output window in Visual Studio (specifically Visual C# Express 2008).

Is there a way to do that?

(Additionally: such that it's not all buffered up and then spat out to the Output window when the child process finishes.)


(BTW: At the moment I can get stdout (but not stderr) of the parent process to appear in the Output window, by making my program a "Windows Application" instead of a "Console Application". This breaks if the program is run outside Visual Studio, but this is ok in my particular case.)

Answer

Mark H picture Mark H · Sep 4, 2010
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();

process.WaitForExit();

Same idea for Error, just replace Output in those method/property names.