process.standardoutput.ReadToEnd()总是空的?

时间:2010-01-06 11:22:39

标签: c# process

我正在启动一个控制台应用程序,但是当我重定向标准输出时,我总是得不到任何东西!

当我不重定向它,并将CreateNoWindow设置为false时,我在控制台中看到了所有内容,但是当我重定向它时,StandardOutput.ReadToEnd()始终返回一个空字符串。

        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

4 个答案:

答案 0 :(得分:15)

最好的方法是重定向输出并等待事件:

    // not sure if all this flags are needed
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.ErrorDialog = false;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += process_OutputDataReceived;
    process.ErrorDataReceived += process_ErrorDataReceived;
    process.Exited += process_Exited;
    process.Start();

    void process_Exited(object sender, System.EventArgs e)
    {
        // do something when process terminates;
    }

    void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        // a line is writen to the out stream. you can use it like:
        string s = e.Data;
    }

    void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        // a line is writen to the out stream. you can use it like:
        string s = e.Data;
    }

答案 1 :(得分:8)

你为什么要循环?一旦它被读到最后,它将无法再读取任何数据,是吗?

您确定文本实际上是写入StandardOutput而不是StandardError吗?

(是的,显然你想将RedirectStandardOutput设置为true而不是false。我认为这只是你复制错误版本代码的情况。)

编辑:正如我在评论中所建议的那样,你应该从单独的线程中的标准输出和标准错误中读取。 not 等待进程退出 - 这可能会导致死锁,等待进程退出,但是进程阻止尝试写入stderr / stdout因为你没有从缓冲区读取。

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

答案 2 :(得分:7)

您已禁用标准输出的重定向。尝试更改

cproc.StartInfo.RedirectStandardOutput = false;

cproc.StartInfo.RedirectStandardOutput = true;

MSDN的以下示例是否适合您?

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

答案 3 :(得分:-1)

摆脱循环,将通话移至ReadToEndcproc_Exited

相关问题