Sep 3, 2012

How to redirect output from a console application?

Tools with user interface offers better User experience than console or command line tools. But in some cases, the application may not have a graphical user interface (GUI),. Eg: .net console applications or nant.

Then, how to show/display output of these type of application or tools in other applications which has GUI to provide more user experience ?

Luckily, Process class (which is available under namespace System.Diagnosticssupports redirection of input, output and error streams instead of normal console output stream. Process class also supports events, which will be raised on error or output data received.

Following code example shows how to do this from .Net Windows Form application. Here, for demo purpose i am using "cmd.exe" as console application and to get help details of "schtasks.exe".

private void RedirectConsoleOutput()
    // Use ProcessStartInfo class
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.UseShellExecute = false;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;

    // Replace "cmd.exe" with your console application
    startInfo.FileName = "cmd.exe";
    // Replace "schtasks.exe /?" with your application parameters or arguments if any required,
    // otherwise ignore this line of code
    startInfo.Arguments = "schtasks.exe /?";

    startInfo.RedirectStandardError = true;
    startInfo.RedirectStandardInput = true;
    startInfo.RedirectStandardOutput = true;

    using (Process process = Process.Start(startInfo))
       process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
       process.EnableRaisingEvents = true;

private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
   // to avoid cross thread blocking and exceptions
   if (rtxtOutput.InvokeRequired)
      rtxtOutput.BeginInvoke(new EventHandler(Process_OutputDataReceived), new object[] { sender, e });

   rtxtOutput.Text += e.Data + Environment.NewLine;

We are done now.


  1. Anonymous5/27/2013

    whats up with the empty posts?

    1. Thanks for the remind me about incomplete posts. Currently doing the clean up or update of existing ones.

      Now this one is updated with solution.