By Gripsoft


2008-10-09 11:27:14 8 Comments

How do I invoke a console application from my .NET application and capture all the output generated in the console?

(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)

7 comments

@Franci Penov 2008-10-09 11:32:20

Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.

Then you can use Process.StandardOutput to read the program output.

The second link has a sample code how to do it.

@Shital Shah 2016-09-21 18:37:20

This is bit improvement over accepted answer from @mdb. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because ReadToEnd() doesn't work if you want to capture both error and regular output. It took me while to make this work because it actually also requires BeginxxxReadLine() calls after Start().

using System.Diagnostics;

Process process = new Process();

void LaunchProcess()
{
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
    process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);
    process.Exited += new System.EventHandler(process_Exited);

    process.StartInfo.FileName = "some.exe";
    process.StartInfo.Arguments = "param1 param2"
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;

    process.Start();
    process.BeginErrorReadLine();
    process.BeginOutputReadLine();          

    //below line is optional if we want a blocking call
    //process.WaitForExit();
}

void process_Exited(object sender, EventArgs e)
{
    Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString()));
}

void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data + "\n");
}

void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data + "\n");
}

@C Bauer 2016-10-11 13:09:13

Thank you, been looking for this for ages!

@Samuel Renkert 2018-08-09 16:24:39

Thank you. This is perfect.

@Sergei Zinovyev 2015-09-09 19:30:53

Added process.StartInfo.**CreateNoWindow** = true; and timeout.

private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
    using (Process process = new Process())
    {
        process.StartInfo.FileName = exeName;
        process.StartInfo.Arguments = arguments;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        output = process.StandardOutput.ReadToEnd();

        bool exited = process.WaitForExit(timeoutMilliseconds);
        if (exited)
        {
            exitCode = process.ExitCode;
        }
        else
        {
            exitCode = -1;
        }
    }
}

@S.Serpooshan 2018-01-01 07:10:28

When you use StandardOutput.ReadToEnd() it won't return to next statement until end of app. so your timeout in WaitForExit(timeoutMilliseconds) does not work! (your code will hang!)

@SlavaGu 2013-03-31 01:36:20

ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.

The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.

Also available as NuGet package.

Sample call to get full console output:

// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
    return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}

Sample with live feedback:

// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
    var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
    var app = new ConsoleApp("ping", url);
    app.ConsoleOutput += (o, args) =>
    {
        var match = regex.Match(args.Line);
        if (match.Success)
        {
            var roundtripTime = match.Groups["time"].Value;
            replyHandler(roundtripTime);
        }
    };
    app.Run();
}

@livetogogo 2010-05-17 16:18:59

From PythonTR - Python Programcıları Derneği, e-kitap, örnek:

Process p = new Process();   // Create new object
p.StartInfo.UseShellExecute = false;  // Do not use shell
p.StartInfo.RedirectStandardOutput = true;   // Redirect output
p.StartInfo.FileName = "c:\\python26\\python.exe";   // Path of our Python compiler
p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py";   // Path of the .py to be executed

@Peter Mortensen 2011-08-12 14:38:05

Can we have it translated?

@Dinis Cruz 2011-11-26 18:02:57

I've added a number of helper methods to the O2 Platform (Open Source project) which allow you easily script an interaction with another process via the console output and input (see http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs)

Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (this blog also contains details of how to consume the console output of new processes)

@Dinis Cruz 2012-12-19 07:52:37

Since then I've added more support for using the ConsoleOut (in this case if you start the .NET process your self). Take a look at: How to use the Console output in the C# REPL , Adding 'Console Out' to VisualStudio IDE as a native Window , Viewing 'Console Out' messages created inside UserControls

@mdb 2008-10-09 11:32:02

This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.

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();    

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();

@tm1 2016-08-08 11:56:27

If you don't want the extra new line at the end, just use Console.Write instead.

@Baaleos 2018-05-04 13:45:35

It should be noted that if you use ReadToEnd() in combination with a console application that has the capability to prompt the user for input. Eg: Overwrite File: Y or N? etc Then ReadToEnd can result in a memory leak, since the process never exits while waiting for user input. The safer way to capture output is to use the process.OutputDataReceived event handler and let the process notify your application of output to be received.

@ryanwebjackson 2018-09-18 16:47:16

Is there a way to do this with an already running Process?

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] If a folder does not exist, create it

  • 2012-01-30 14:42:14
  • Tavousi
  • 649976 View
  • 586 Score
  • 15 Answer
  • Tags:   c# asp.net folder

15 Answered Questions

[SOLVED] How do I exit a WPF application programmatically?

  • 2010-05-12 15:37:11
  • anon271334
  • 293002 View
  • 417 Score
  • 15 Answer
  • Tags:   c# .net wpf shutdown

26 Answered Questions

[SOLVED] How can I get the application's path in a .NET console application?

26 Answered Questions

[SOLVED] Get int value from enum in C#

  • 2009-06-03 06:46:39
  • jim
  • 1252790 View
  • 1530 Score
  • 26 Answer
  • Tags:   c# enums casting int

42 Answered Questions

[SOLVED] How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 980936 View
  • 1696 Score
  • 42 Answer
  • Tags:   c# .net excel file-io

13 Answered Questions

12 Answered Questions

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

10 Answered Questions

[SOLVED] No output to console from a WPF application?

  • 2008-10-02 02:12:03
  • Rob
  • 90822 View
  • 92 Score
  • 10 Answer
  • Tags:   c# .net wpf console

7 Answered Questions

[SOLVED] rails - Redirecting console output to a file

Sponsored Content