Home > Net >  OutputDataReceived not firing as expected
OutputDataReceived not firing as expected

Time:06-28

I am trying to launch an external command line application and get the output of that command line application, but OutputDataReceived is not firing as expected

To illustrate the problem I'm using ping.exe so others can reproduce it, but the actual application is an application from a third party that we use and I want to parse info, warning, error, and progress messages that the application returns.

If you run the command "ping.exe localhost" you get output that looks something like what is shown below, and it's this kind of output that I am trying to get

Pinging my.local.computer.name [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms

Ping statistics for ::1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

using var process = new Process();

var processInfo = new ProcessStartInfo("ping.exe", "localHost");
processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = true;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;

process.StartInfo = processInfo;
process.EnableRaisingEvents = true;
process.OutputDataReceived  = (sender, args) => Console.WriteLine(args.Data);
process.ErrorDataReceived  = (sender, args) => Console.WriteLine(args.Data);
process.Exited  = (sender, args) => Console.WriteLine("ping finished.");

process.Start();
await process.WaitForExitAsync();

With the above code, I would expect to get OutputDataReceived events for each line of output from ping.exe, but instead, the only event that is fired is the Exited event.

CodePudding user response:

You're missing a call to process.BeginOutputReadLine();

process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
  • Related