25

Duplicate

Redirect console output to textbox in separate program Capturing nslookup shell output with C#

I am looking to call an external program from within my c# code.

The program I am calling, lets say foo.exe returns about 12 lines of text.

I want to call the program and parse thru the output.

What is the most optimal way to do this ?

Code snippet also appreciated :)

Thank You very much.

Community
  • 1
  • 1

1 Answers1

65
using System;
using System.Diagnostics;

public class RedirectingProcessOutput
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c dir *.cs";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        Console.WriteLine("Output:");
        Console.WriteLine(output);    
    }
}
dario_ramos
  • 7,118
  • 9
  • 61
  • 108
Stormenet
  • 25,926
  • 9
  • 53
  • 65
  • 7
    Almost. You need to call WaitForExit() after ReadToEnd(), to avoid blocking issues. – Michael Petrotta May 18 '09 at 16:54
  • Just did that since the answer worked for me with that correction – dario_ramos Aug 12 '11 at 15:21
  • I am not so sure about the interaction (and order) of `ReadToEnd` and `WaitForExit`. For example, read [here](http://multipleinheritance.wordpress.com/2012/07/31/process-waitforexit-and-exited-event-arent-working/). – darda Aug 23 '14 at 23:59
  • 7
    In longer programs, remember to dispose the process or use it in a `using(Process pProcess = new Process()) { }` block – pKami Sep 21 '16 at 17:43