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.

1

1 Answer 1

66
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);    
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Almost. You need to call WaitForExit() after ReadToEnd(), to avoid blocking issues.
Just did that since the answer worked for me with that correction
I am not so sure about the interaction (and order) of ReadToEnd and WaitForExit. For example, read here.
In longer programs, remember to dispose the process or use it in a using(Process pProcess = new Process()) { } block

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.