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

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

问题描述

我正在启动一个控制台应用程序,但是当我重定向标准输出时,我总是一无所获!

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

当我不重定向它并将 CreateNoWindow 设置为 false 时,我可以在控制台中正确地看到所有内容,但是当我重定向它时,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();
        }

EventHandler cproc_exited 只是将 stop 设置为 true.有人能解释一下为什么 result 总是 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 设置为 true 而不是 false.我认为这只是您复制了错误版本代码的情况.)

(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/stdout,因为您没有不从缓冲区读取.

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天全站免登陆