Proposed solutions with BeginOutputReadLine()
are a good way but in situations such as that, it is not applicable, because process (certainly with using WaitForExit()
) exits earlier than async output finished completely.
So, I tried to implement it synchronously and found that the solution is in using Peek()
method from StreamReader
class. I added check for Peek() > -1
to sure that it is not the end of the stream as in MSDN article described and finally it works and stop hanging!
Here is the code:
var process = new Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = @"C:est";
process.StartInfo.FileName = "test.exe";
process.StartInfo.Arguments = "your arguments here";
process.Start();
var output = new List<string>();
while (process.StandardOutput.Peek() > -1)
{
output.Add(process.StandardOutput.ReadLine());
}
while (process.StandardError.Peek() > -1)
{
output.Add(process.StandardError.ReadLine());
}
process.WaitForExit();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…