0
Answer

Process / ErrorDataReceived / OutputDataReceived

James C

James C

17y
7.1k
1

I'm running an exe (which writes to output and error), from another. How do I process / catch that output in the order that it has been written?

For example, in the below code, if I run OutputTest.exe I get

out line 1
error line 1
out line 2
error line 2

But if I run ProcessTest.exe I get

error line 1
error line 2
out line 1
out line 2


Thanks in advance,

James


-- Code --

OutputTest.exe

static void Main(string[] args)
{
 Console.Out.WriteLine("out line 1");
 Console.Out.Flush();
 Console.Error.WriteLine("error line 1");
 Console.Error.Flush();
 Console.Out.WriteLine("out line 2");
 Console.Out.Flush();
 Console.Error.WriteLine("error line 2");
 Console.Error.Flush();
}


ProcessTest.exe


private void runButton_Click(object sender, EventArgs e)
{
 this.backgroundWorker1.RunWorkerAsync();
 while (this.backgroundWorker1.IsBusy)
 {
  Application.DoEvents();
 }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
 using (Process proc = new Process())
 {
  proc.StartInfo.FileName = "OutputTest.exe";
  proc.StartInfo.WorkingDirectory = Application.StartupPath;
  proc.StartInfo.UseShellExecute = false;
  proc.StartInfo.CreateNoWindow = true;
  proc.StartInfo.RedirectStandardError = true;
  proc.StartInfo.RedirectStandardOutput = true;
  proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessErrorHandler);
  proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
  proc.Start();
  proc.BeginErrorReadLine();
  proc.BeginOutputReadLine();
  proc.WaitForExit();
  proc.Close();
 }
}

private void ProcessErrorHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
 Console.WriteLine(outLine.Data);
}
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
 Console.WriteLine(outLine.Data);
}