views:

3082

answers:

3

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 to hard with the callback. doing:

return p.StandardOutput.ReadToEnd();

Appears to work fine.

A: 

You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.

SoapBox
that was a typo, as I was removing some code to make a sample, I accidently cut that line out.
FlySwat
+3  A: 

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();
Judah Himango
+2  A: 

It looks like two of your lines are out of order. You start the process before setting up an event handler to capture the output. It's possible the process is just finishing before the event handler is added.

Switch the lines like so.

p.OutputDataReceived += ...
p.Start();
JaredPar