process.standardoutput.ReadToEnd()总是空的? [英] process.standardoutput.ReadToEnd() always empty?

查看:2188
本文介绍了process.standardoutput.ReadToEnd()总是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始一个控制台应用程序,但是当我重定向标准输出我总是得到什么!

I'm starting a console application, but when I redirect the standard output I always get nothing!

当我不重定向它,并设置 CreateNoWindow ,我没有在控制台中看到的一切,但是当我把它重定向, StandardOutput。 。ReadToEnd的()总是返回一个空字符串

When I don't redirect it, and set CreateNoWindow to false, I see everything correctly in the console, but when I redirect it, StandardOutput.ReadToEnd() always returns an empty string.

        Process cproc = new Process();
        cproc.StartInfo.CreateNoWindow = true;
        cproc.StartInfo.FileName = Dest;
        cproc.StartInfo.RedirectStandardOutput = true;
        cproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        cproc.StartInfo.UseShellExecute = false;
        cproc.EnableRaisingEvents = true;
        cproc.Start();
        cproc.Exited += new EventHandler(cproc_Exited);
        while(!stop)
        {
           result += cproc.StandardOutput.ReadToEnd();
        }



事件处理cproc_exited 只是设置停止真正。有人可以解释为什么结果总是的String.Empty

The EventHandler cproc_exited just sets stop to true. Can someone explain why result is always string.Empty?

推荐答案

你为什么循环?一旦它的读取到最后,它不会是能够读取任何数据,是吗?

Why are you looping? Once it's read to the end, it's not going to be able to read any more data, is it?

您确定该文本实际上是被写入 StandardOutput ,而不是 StandardError的

Are you sure the text is actually being written to StandardOutput rather than StandardError?

(是的,很显然你希望设置 RedirectStandardOutput 来真正的而不是虚假的。我以为那只是你复制代码的错版的情况。)

(And yes, obviously you want to set RedirectStandardOutput to true rather than false. I assumed that was just a case of you copying the wrong version of your code.)

编辑:正如我在评论中所建议,你应该从单独的线程标准输出和标准错误。做的的等到进程已退出 - 这可以用一个僵局,在你等待的过程中退出结束了,但过程是阻止试图写入到stderr /标准输出,因为你的避风港'T从缓冲区中读取。

As I've advised in the comments, you should read from standard output and standard error in separate threads. Do not wait until the process has exited - this can end up with a deadlock, where you're waiting for the process to exit, but the process is blocking trying to write to stderr/stdout because you haven't read from the buffer.

另外,您可以订阅OutputDataReceived和ErrorDataReceived事件,避免使用额外的线程。

Alternatively you can subscribe to the OutputDataReceived and ErrorDataReceived events, to avoid using extra threads.

这篇关于process.standardoutput.ReadToEnd()总是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆