首頁 >後端開發 >C++ >如何從C#中的.NET應用程序中捕獲實時控制台輸出?

如何從C#中的.NET應用程序中捕獲實時控制台輸出?

Barbara Streisand
Barbara Streisand原創
2025-01-29 12:21:12631瀏覽

How to Capture Real-time Console Output from .NET Applications in C#?

在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類存儲有關要執行的可執行文件的信息。
  • 設置FileNameArguments屬性以指定要調用的控制台應用程序。
  • 禁用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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn