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?
Here is what I've used, without using a separate thread:
using(System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.EnableRaisingEvents = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Verb = "open";
proc.StartInfo.FileName = "XXXX";
proc.Start();
String sLine = "";
while ((sLine = proc.StandardOutput.ReadLine()) != null)
{
System.Console.WriteLine(sLine);
}
proc.WaitForExit(); //Jon Skeet was here!
errorCode = proc.ExitCode;
proc.Close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With