【问题标题】:Getting data from Process.StandardOutput on the fly即时从 Process.StandardOutput 获取数据
【发布时间】:2013-08-31 00:07:21
【问题描述】:

我正在尝试从 Process.StandardOutput 获取数据......但我有一个问题:我在进程结束时获取数据,但在执行期间没有(它不刷新???)。看起来数据缓冲在某处。 当我手动运行该过程时,消息会在执行期间出现。如何解决?

【问题讨论】:

    标签: c# process stdout stderr autoflush


    【解决方案1】:

    这是我用来从进程中获取输出的方法。这是添加到字符串生成器,但您可以做其他事情。

        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;
        }
    

    【讨论】:

    • 可能是因为EOL风格不同?
    • 不,streamreader 支持 3 种最常用的 EOL 样式。问题出在其他地方
    猜你喜欢
    • 2012-09-12
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2021-02-15
    • 2016-11-22
    • 2020-05-26
    相关资源
    最近更新 更多