相关疑难解决方法(0)

如何在.NET中生成进程并捕获其STDOUT?

我需要生成一个作为控制台应用程序的子进程,并捕获其输出.

我为方法编写了以下代码:

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)

似乎工作正常.

.net c# process spawning

133
推荐指数
7
解决办法
11万
查看次数

标签 统计

.net ×1

c# ×1

process ×1

spawning ×1