如何在 .NET 中生成进程并捕获其 STDOUT? [英] How to spawn a process and capture its STDOUT in .NET?
本文介绍了如何在 .NET 中生成进程并捕获其 STDOUT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要生成一个作为控制台应用程序的子进程,并捕获其输出.
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;
然而,这不会返回任何东西.我不相信 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();
看起来工作正常.
推荐答案
这是我已经验证可以工作的代码.我用它来生成 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 中生成进程并捕获其 STDOUT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文