【问题标题】:Streamreader readline returning null value from process execution [duplicate]Streamreader readline从流程执行返回空值[重复]
【发布时间】:2019-05-11 23:30:00
【问题描述】:

我正在尝试逐行获取流程的输出,但我得到了返回的空值。你能检查我下面的代码,让我知道我在这里做错了什么吗?请推荐

Process process = new Process();
process.StartInfo.FileName = dirPath + "\\test.exe";
process.StartInfo.Arguments = "-a -h -s " + dir;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();

using (StreamReader streamReader = Process.StandardOutput)
{
    string line = streamReader.ReadLine();
    while (line != null)
    {
        Console.WriteLine(line);
    }
}
process.WaitForExit();

如果我使用string line = streamReader.ReadToEnd(),它会显示所有行。

【问题讨论】:

  • 在while中使用断点,检查该行是否真的有值?
  • 您不是在等待该过程完成吗?
  • @HEWhoDoesn'tKnow:当我使用 ReadLine() 时它没有任何价值。
  • @Amy 对不起,我在复制粘贴中错过了它。刚刚更新
  • 为什么不等它退出得到它的输出?

标签: c#


【解决方案1】:

我可以通过进行以下更改来解决此问题。我需要在 while 循环中添加 !streamReader.EndOfStream ,然后使用对我有用的 streamReader.ReadLine() 逐行解析。

                Process process = new Process();
                process.StartInfo.FileName = Pathdir + "\\test.exe";
                process.StartInfo.Arguments = "-a -h -s " + dir;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.Start();

                using (StreamReader streamReader = process.StandardOutput)
                {
                    while (!streamReader.EndOfStream)
                    {
                        string line = streamReader.ReadLine();
                        Console.WriteLine(line);
                    }
                }

【讨论】:

  • 如果你想给出一个合适的答案,解释你做了什么,只是不要粘贴代码块,解释为什么你认为它有效,添加任何支持它的文档
  • @TheGeneral 我正在尝试学习编码方面,但仍处于起步阶段。所以我目前的方法是基于试错法和你提供的输入。如果我能够明确解释,我会在未来将我的观点添加到数据中。
猜你喜欢
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多