在.NET应用程序中
实时控制台输出捕获
此示例显示了如何实时在.NET应用程序中捕获和显示控制台应用程序的输出。
<code class="language-csharp">using System.Diagnostics; namespace RealtimeConsoleOutput { class Program { static void Main(string[] args) { // Initiate the process for the console application. Process consoleApp = new Process(); // Configure process settings. consoleApp.StartInfo.FileName = "csc.exe"; // Assumes 'csc.exe' is in the system PATH consoleApp.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs"; consoleApp.StartInfo.UseShellExecute = false; consoleApp.StartInfo.RedirectStandardOutput = true; // Begin the process. consoleApp.Start(); // Continuously read and display output. while (!consoleApp.StandardOutput.EndOfStream) { string line = consoleApp.StandardOutput.ReadLine(); if (!string.IsNullOrEmpty(line)) // added null check for robustness Console.WriteLine(line); } // Wait for the console application to finish. consoleApp.WaitForExit(); } } }</code>
详细说明:
ProcessStartInfo.RedirectStandardOutput = true
while
consoleApp.StandardOutput
Console.WriteLine()
:这检查是否已收到所有输出。consoleApp.StandardOutput.EndOfStream
:这确保.NET应用程序等待控制台应用程序的完成。consoleApp.WaitForExit()
要进行全面的输出捕获,请考虑使用以上是如何从.NET应用程序中捕获和显示实时控制台输出?的详细内容。更多信息请关注PHP中文网其他相关文章!