进程StandartOutput.ReadLine()挂起

时间:2016-11-18 14:34:12

标签: c# cmd process streamreader readline

嘿,我试图从cmd.exe读取输出流 这是使用的代码

string r = string.Empty;
while(!cmd.StandardOutput.EndOfStream)
     {
       r = cmd.StandardOutput.ReadLine(); /*the app hangs here after trying to read the last line*/
       MessageBox.Show(r);
     }

还尝试了:

StreamReader reader = cmd.StandardOutput;
cmd.Close();
while(!reader.EndOfStream)
     {
       r = reader.ReadLine(); /*the app hangs here after trying to read the last line*/
       MessageBox.Show(r);
     }    

再次出现同样的问题。

我用peek()> = 0替换了EndOfStream没有工作 尝试使用CopyTo()方法将cmd.StandardOutput的基本流复制到另一个流中,但它并没有为我工作

应该添加

            cmd.StandardInput.WriteLine("exit");

从输出流

读取之前

感谢Hans Passant

  

预计,在发送之前不会退出该循环   EXIT命令,因此它关闭其输出流。不读书   StandardError也是一种很好的死锁方法。这只是永远   使用BeginOutput / ErrorReadLine()时效果很好。

- Hans Passant

1 个答案:

答案 0 :(得分:0)

ReadLine()返回输入流中的下一行,如果到达输入流的末尾,则返回null。所以你可以这样做:

var line = reader.ReadLine();
while(line != null)
{
    MessageBox.Show(line);
    line = reader.ReadLine();
}
相关问题