从.NET应用程序(C#)捕获控制台输出
问题描述:
如何从我的.NET应用程序调用控制台应用程序并捕获控制台中生成的所有输出?
How do I invoke a console application from my .NET application and capture all the output generated in the console?
(请记住,我不想将信息保存在文件中,然后重新生成,因为我希望能够接收它。)
(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)
答
这可以很容易地使用 ProcessStartInfo.RedirectStandardOutput 属性。完整的示例包含在链接的MSDN文档中;唯一的警告是,您可能必须重定向标准错误流以查看您的应用程序的所有输出。
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();