将子进程的输出(stdout、stderr)重定向到 Visual Studio 中的输出窗口 [英] Redirect the output (stdout, stderr) of a child process to the Output window in Visual Studio
问题描述
目前我正在从我的 C# 程序启动一个批处理文件:
At the moment I am starting a batch file from my C# program with:
System.Diagnostics.Process.Start(@"DoSomeStuff.bat");
我希望能够做的是将该子进程的输出(stdout 和 stderr)重定向到 Visual Studio(特别是 Visual C# Express 2008)中的输出窗口.
What I would like to be able to do is redirect the output (stdout and stderr) of that child process to the Output window in Visual Studio (specifically Visual C# Express 2008).
有没有办法做到这一点?
Is there a way to do that?
(另外:这样它不会全部被缓冲,然后在子进程完成时吐出到输出窗口.)
(Additionally: such that it's not all buffered up and then spat out to the Output window when the child process finishes.)
(顺便说一句:目前我可以通过使我的程序成为Windows 应用程序"而不是控制台"来使 父 进程的标准输出(但不是标准错误)出现在输出窗口中应用程序".如果程序在 Visual Studio 之外运行,这会中断,但在我的特殊情况下这没问题.)
(BTW: At the moment I can get stdout (but not stderr) of the parent process to appear in the Output window, by making my program a "Windows Application" instead of a "Console Application". This breaks if the program is run outside Visual Studio, but this is ok in my particular case.)
推荐答案
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
Error
的想法相同,只需替换那些方法/属性名称中的 Output
.
Same idea for Error
, just replace Output
in those method/property names.
这篇关于将子进程的输出(stdout、stderr)重定向到 Visual Studio 中的输出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!