我需要生成一个作为控制台应用程序的子进程,并捕获其输出.
我为方法编写了以下代码:
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;
Run Code Online (Sandbox Code Playgroud)
但是,这不会返回任何内容.我不相信该OutputDataReceived事件被回调,或者该WaitForExit()命令可能阻塞该线程,因此它永远不会回调.
有什么建议?
编辑:看起来我在回调中努力了.这样做:
return p.StandardOutput.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
似乎工作正常.