Is there a way to get process output the same way It’s written when the process is launched through shell? Basically I need to launch some external processes (A&B). When I launch them through cmd or with UseShellExecute = true the output is printed continuously. Process A prints its progress line by line. Process B displays and updates a text-based progress bar.
For process A, OutputDataReceived does not fire after each output line that is normally printed if the process is launched through shell. It fires after each 20 lines approximately (it fires 20 times so I have the whole output, but I can’t capture the output in real time). I guess that it fires after stdOut is flushed, but then how cmd does it to print partial output and what can I do to read it?
For process B, OutputDataReceived fires only once the process is done.
My code:
public static bool ExecuteProcess(string Path, string CommandLine, Action<string> OutputLineDelegate)
{
using (Process ChildProcess = new Process())
{
ChildProcess.StartInfo.FileName = Path;
ChildProcess.StartInfo.Arguments = CommandLine;
ChildProcess.StartInfo.UseShellExecute = false;
ChildProcess.StartInfo.CreateNoWindow = true;
ChildProcess.StartInfo.RedirectStandardOutput = true;
ChildProcess.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
{
OutputLineDelegate(e.Data);
};
ChildProcess.Start();
ChildProcess.WaitForExit();
var ExitCode = ChildProcess.ExitCode;
OutputLineDelegate(string.Format("Exit code {0}", ExitCode));
return ExitCode == 0 ? true : false;
}
}
I’ve tried to reading stdOut char by char, but both StreamReader.Read() and StreamReader.Peek() wait until anything is in the output.