How to spawn a process and capture its STDOUT in .NET?

FlySwat picture FlySwat · Nov 13, 2008 · Viewed 119.5k times · Source

I need to spawn a child process that is a console application, and capture its output.

I wrote up the following code for a method:

string retMessage = String.Empty;
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();

startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;

startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = exec;

p.StartInfo = startInfo;
p.Start();

p.OutputDataReceived += new DataReceivedEventHandler
(
    delegate(object sender, DataReceivedEventArgs e)
    {
        using (StreamReader output = p.StandardOutput)
        {
            retMessage = output.ReadToEnd();
        }
    }
);

p.WaitForExit();

return retMessage;

However, this does not return anything. I don't believe the OutputDataReceived event is being called back, or the WaitForExit() command may be blocking the thread so it will never callback.

Any advice?

EDIT: Looks like I was trying too hard with the callback. Doing:

return p.StandardOutput.ReadToEnd(); 

Appears to work fine.

Answer

Judah Gabriel Himango picture Judah Gabriel Himango · Nov 13, 2008

Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();