在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中文網其他相關文章!