在C#中实时捕获.NET应用程序控制台输出
问题:
.NET应用程序开发者在集成控制台应用程序时,常常面临捕获控制台应用程序生成的输出的挑战。如何在不依赖基于文件的方法的情况下实时捕获此输出?
解决方案:
利用ProcessStartInfo.RedirectStandardOutput
属性将控制台应用程序的输出重定向到.NET应用程序中的流。
实现:
以下C#代码片段演示了如何调用控制台应用程序并捕获其输出:
<code class="language-csharp">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(); string output = compiler.StandardOutput.ReadToEnd(); Console.WriteLine(output); compiler.WaitForExit();</code>
说明:
ProcessStartInfo
类存储有关要执行的可执行文件的信息。FileName
和Arguments
属性以指定要调用的控制台应用程序。UseShellExecute
以更好地控制进程执行。RedirectStandardOutput
将控制台的标准输出重定向到当前进程中的流。Start()
执行控制台应用程序。ReadToEnd()
读取流直到其结束,捕获控制台应用程序的所有输出。WaitForExit()
等待控制台应用程序完成执行后再继续执行。This revised response maintains the original image and its format while rewording the text for improved clarity and flow. Key terms are also slightly altered to avoid direct copying.
以上是如何从C#中的.NET应用程序中捕获实时控制台输出?的详细内容。更多信息请关注PHP中文网其他相关文章!