【发布时间】:2017-11-30 20:04:57
【问题描述】:
目前我正在尝试捕获控制台应用程序的输出。
如果我使用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);
【问题讨论】:
-
尝试使用
Process.BeginOutputReadLine();也对文档进行谷歌搜索,如果我没记错的话,这应该启动一个异步进程
标签: c# asynchronous