即时从Process.StandardOutput获取数据

时间:2013-08-31 00:07:21

标签: c# process stdout stderr autoflush

我正在尝试从Process.StandardOutput获取数据...但我遇到了一个问题:我在进程结束时获取数据,但在执行期间没有(没有刷新???)。看起来数据在某处缓冲。 当我在执行过程中手动运行该过程时,会显示消息。怎么解决?

1 个答案:

答案 0 :(得分:0)

这是我用来从进程中获取输出的东西。这是添加到stringbuilder,但你可以做其他事情。

    private void RunWithOutput(string exe, string parameters, out string result, out int exitCode)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo(exe, parameters);
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardError = true;
        startInfo.RedirectStandardOutput = true;
        Process p = new Process();
        p.StartInfo = startInfo;

        p.Start();

        StringBuilder sb = new StringBuilder();
        object locker = new object();
        p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args) 
        {
            lock(locker)
            {
                sb.Append(args.Data);
            }
        } );
        p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args)
        {
            lock (locker)
            {
                sb.Append(args.Data);
            }
        });

        p.BeginErrorReadLine();
        p.BeginOutputReadLine();

        p.WaitForExit();
        result = sb.ToString();
        exitCode = p.ExitCode;
    }