Real-time Console Output Capture in .NET Applications
This example shows how to capture and display the output of a console application within a .NET application in real time.
<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>
Detailed Explanation:
ProcessStartInfo.RedirectStandardOutput = true
: This redirects the console application's standard output to the .NET application.while
loop continuously reads lines from consoleApp.StandardOutput
and displays them using Console.WriteLine()
. The addition of a null check improves the code's robustness.consoleApp.StandardOutput.EndOfStream
: This checks if all output has been received.consoleApp.WaitForExit()
: This ensures the .NET application waits for the console application's completion.For comprehensive output capture, consider redirecting the standard error stream using RedirectStandardError = true
.
The above is the detailed content of How Can I Capture and Display Live Console Output from a .NET Application?. For more information, please follow other related articles on the PHP Chinese website!