Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture standard output and still display it in the console window

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?

like image 769
mjl5007 Avatar asked Apr 24 '09 16:04

mjl5007


1 Answers

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();
}
like image 136
crashmstr Avatar answered Sep 17 '22 17:09

crashmstr