I have managed to redirect the output of a console application to my WPF program using StandardOutput, but the console application sends data just before closing. Here is my code:
ProcessStartInfo info = new ProcessStartInfo("c:/program.exe"); info.RedirectStandardOutput = true; info.RedirectStandardError = true; info.RedirectStandardInput = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; Process process = new Process(); process.StartInfo = info; info.UseShellExecute = false; process.OutputDataReceived += new DataReceivedEventHandler( (s, e1) => {
//This is where I get an "Object reference not set to an instance of an object if (e1.Data.Contains("USB connected")) { //Do stuff here } } ); process.Start(); process.BeginOutputReadLine();
I suspect this is because by the time the OutputDataReceived event has fired, the console application has closed, taking the data with it.
Even though I think I understand what is going on, I can't find anyone who seems to have had the same problem, and I have no idea how this can be fixed. Is there any way of stopping the process from closing itself automatically, and using Process.Kill() once I have the data?