捕获标准输出并仍然将其显示在控制台窗口中
我正在生成一个在可见控制台窗口中运行的子进程(它是运行 MSBuild 的批处理文件),并且我希望将进程生成的输出显示在可见控制台窗口中,并捕获该输出所以我可以用代码处理它。 我已经阅读了其他几个问题以及处理 ProcessStartInfo.RedirectStandardOutput 等的 MSDN 文档,我可以捕获重定向流的输出并在代码中很好地处理它:
Process msBuild = new Process();
msBuild.StartInfo.FileName = "Build.bat";
msBuild.StartInfo.UseShellExecute = false;
msBuild.StartInfo.RedirectStandardOutput = true;
msBuild.Start();
string output = msBuild.StandardOutput.ReadToEnd();
msBuild.WaitForExit();
问题是输出没有显示在控制台中子进程的窗口; 当进程运行时,我只是在屏幕上看到一个空白的控制台窗口,该窗口在完成后消失。
我想我可以隐藏实际的子进程窗口,并显示第二个窗口,我只需在捕获时将输出写入其中,但这似乎比必要的工作更多。 有没有办法让输出显示在控制台窗口中,并在完成后仍然捕获它进行处理?
I'm spawning a child process that runs in a visible console window (it's a batch file that runs MSBuild), and I'd like to have the output generated by the process displayed in the visible console window, as well as capture that output so I can process it in code. I've read several other questions and the MSDN documentation dealing with ProcessStartInfo.RedirectStandardOutput and the like, and I can capture the output from the redirected stream and process it in code just fine:
Process msBuild = new Process();
msBuild.StartInfo.FileName = "Build.bat";
msBuild.StartInfo.UseShellExecute = false;
msBuild.StartInfo.RedirectStandardOutput = true;
msBuild.Start();
string output = msBuild.StandardOutput.ReadToEnd();
msBuild.WaitForExit();
The problem is that the output is not displayed in the console window of the child process; I just get a blank console window on the screen while the process is running, which disappears when it's finished.
I suppose I could hide the actual child process window, and display a second window that I would simply write the output to as it was captured, but that seems like more work than is necessary. Is there a way to have the output displayed in the console window and still capture it for processing when it's done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我使用的,没有使用单独的线程:
Here is what I've used, without using a separate thread:
一旦您重定向标准输出,它就不再指向控制台。 要写入控制台,您必须手动执行。
如果您想在流程执行时显示输出,而不是在最后显示 1 个大转储,您可以使用 Process 类的“OutputDataReceived”事件。
Once you've redirected standard out it's no longer directed at the console. To write to the console you'll have to do it manually.
If you want to display output as the process executes, instead of in 1 big dump at the end, you can use the "OutputDataReceived" event of the Process class.