如何产卵一个过程,捕获它的标准输出。NET中? [英] How to spawn a process and capture its STDOUT in .NET?

查看:192
本文介绍了如何产卵一个过程,捕获它的标准输出。NET中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个子进程是一个控制台应用程序,并捕获它的输出。

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

我写了下面的code的方法:

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;

然而,这不返回任何东西。我不相信 OutputDataReceived 事件被称为回,或 WaitForExit()命令可能会阻塞线程所以它永远不会回调。

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.

任何意见?

编辑:看起来像我试图太硬的回调。这样做的:

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

return p.StandardOutput.ReadToEnd(); 

出现很好地工作。

Appears to work fine.

推荐答案

下面是我已经验证工作,code。我用它产卵的MSBuild,听其输出:

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

这篇关于如何产卵一个过程,捕获它的标准输出。NET中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆