R – Capture standard output and still display it in the console window

netprocessstdout

I'm spawning a child process that runs in a visible console window (it's a batch file that runs MSBuild), and I'd like to have the output generated by the process displayed in the visible console window, as well as capture that output so I can process it in code. I've read several other questions and the MSDN documentation dealing with ProcessStartInfo.RedirectStandardOutput and the like, and I can capture the output from the redirected stream and process it in code just fine:

Process msBuild = new Process();
msBuild.StartInfo.FileName = "Build.bat";
msBuild.StartInfo.UseShellExecute = false;
msBuild.StartInfo.RedirectStandardOutput = true;
msBuild.Start();
string output = msBuild.StandardOutput.ReadToEnd();
msBuild.WaitForExit();

The problem is that the output is not displayed in the console window of the child process; I just get a blank console window on the screen while the process is running, which disappears when it's finished.

I suppose I could hide the actual child process window, and display a second window that I would simply write the output to as it was captured, but that seems like more work than is necessary. Is there a way to have the output displayed in the console window and still capture it for processing when it's done?

Best Answer

Once you've redirected standard out it's no longer directed at the console. To write to the console you'll have to do it manually.

If you want to display output as the process executes, instead of in 1 big dump at the end, you can use the "OutputDataReceived" event of the Process class.