【发布时间】:2010-09-22 02:16:24
【问题描述】:
我需要生成一个作为控制台应用程序的子进程,并捕获其输出。
我为一个方法编写了以下代码:
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() 命令可能会阻塞线程,因此它永远不会回调。
有什么建议吗?
编辑: 看起来我在回调方面太努力了。正在做:
return p.StandardOutput.ReadToEnd();
看起来工作正常。
【问题讨论】:
-
如果您不打算与应用程序交互而只关心其输出,则不应使用异步
BeginOutputReadLine()和Start()的方式来执行此操作。我发现这些不是很可靠,它们有时会截断应用程序输出的开头。 -
为什么不
retMessage = e.Data?这已经是一个字符串变量了:)