I have problem with reading the output of one Process asynchronously in C#.
I found some other similar questions on this site but they don't really help me.
Here is what I do:
- Make new process
- Set startinfo
-FileName, Arguments, CreateNoWindow(true), UseShellExecute(false), RedirectStandardOutput(true) - Add event handler to OutputDataReceived;
- Start process, BeginOutputReadLine and then WaitForExit().
It works fine but the output of the started process writes some percents(%
) which I want to get but I can't since my code reads line by line and the percents don't show up.
Example:
%0,%1...%100
Finished.
My output:
%0
Finished.
Here is the current code of my program:
StringBuilder sBuilder = new StringBuilder();
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
sBuilder.AppendLine(e.Data);
}
static void CommandExecutor()
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = /*path of the program*/,
Arguments = /*arguments*/,
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
Best Answer
Process.WaitForExit()
will wait until the asynchronous output / error stream reading finished. Unfortunately this is not true forProcess.WaitForExit(timeout)
overload. This is what theProcess
class does internally://...
... So it will wait for the async reads only if there was no timeout! To fix it simply call the
parameterless WaitForExit()
afterWaitForExit(timeout)
returned true:// ...
For details read the remarks here: http://msdn.microsoft.com/en-us/library/ty0d8k56%28v=vs.110%29