目前我正在尝试捕获控制台应用程序的输出。
如果我使用StandardOutput.ReadToEnd()
方法,我可以正确捕获输出,但如果我使用OutputDataReceived
,则永远不会调用该事件。
我的代码:
Process testProcess = new Process();
testProcess.StartInfo.FileName = "teste.exe";
testProcess.StartInfo.UseShellExecute = false;
testProcess.StartInfo.RedirectStandardOutput = true;
testProcess.StartInfo.RedirectStandardError = true;
testProcess.StartInfo.RedirectStandardInput = true;
testProcess.EnableRaisingEvents = true;
testProcess.Start();
StreamWriter myStreamWriter = testProcess.StandardInput;
myStreamWriter.Write("a"); // press any key to continue
// var output = testProcess.StandardOutput.ReadToEnd(); // this works all the times
StringBuilder output = new StringBuilder();
testProcess.OutputDataReceived += (sender, e) => {
// never raised
if (e.Data != null)
output.AppendLine("'" + e.Data + "'");
};
testProcess.WaitForExit();
Console.WriteLine(output);
答案 0 :(得分:2)
阅读documentation of OutputDataReceived
,您必须致电testProcess.BeginOutputReadLine()
。
您可能必须在设置testProcess.Start()
事件后调用OutputDataReceived
,如示例所示。