【问题标题】:Process StandartOutput.ReadLine() Hangs进程 StandartOutput.ReadLine() 挂起
【发布时间】:2016-11-18 14:34:11
【问题描述】:

嘿,我正在尝试从 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);
     }    

又是同样的问题。

我已将 EndOfStream 替换为 peek()>=0 无效 尝试使用 CopyTo() 方法将 cmd.StandardOutput 的基本流复制到另一个流中,但它对我不起作用

解决方案 应该添加

            cmd.StandardInput.WriteLine("exit");

从输出流中读取之前

感谢汉斯·帕桑特

这是预期的,在您发送之前它不会退出该循环 EXIT 命令,以便它关闭其输出流。不读书 StandardError 也是一个很好的死锁方法。这只曾经 使用 BeginOutput/ErrorReadLine() 时效果很好。

– 汉斯·帕桑特

【问题讨论】:

  • 这是意料之中的,在您向其发送 EXIT 命令以关闭其输出流之前,它不会退出该循环。不阅读 StandardError 也是一个很好的死锁方法。这只有在您使用 BeginOutput/ErrorReadLine() 时才能正常工作。
  • 哦,谢谢,这就是解决方案

标签: c# cmd process streamreader readline


【解决方案1】:

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

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

【讨论】:

  • 不工作,因为它在返回任何东西之前挂起
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多