【问题标题】:StreamReader.ReadToEnd() returns empty string [duplicate]StreamReader.ReadToEnd() 返回空字符串 [重复]
【发布时间】:2018-09-27 20:44:20
【问题描述】:

我正在尝试在 cmd.exe 中运行命令,并将输出重定向到文本文件。我已经验证该命令正在执行,但是当我调用 StandardOutput.ReadToEnd() 或 StandardError.ReadToEnd() 时,将返回一个空字符串而不是命令的文本输出。我错过了什么吗?

    ProcessStartInfo PSI = new ProcessStartInfo("cmd.exe", command);

    PSI.UseShellExecute = false;
    PSI.CreateNoWindow = true;
    PSI.RedirectStandardInput = true;
    PSI.RedirectStandardOutput = true;
    PSI.RedirectStandardError = true;
    PSI.Arguments = "/c";

    var proc = Process.Start(PSI);
    proc.WaitForExit();

    string output = proc.StandardOutput.ReadToEnd();
    Console.WriteLine(output);

    string errors = proc.StandardError.ReadToEnd();
    Console.WriteLine(errors);

【问题讨论】:

标签: c# cmd streamreader


【解决方案1】:

如果您同时捕获错误输出,我很确定使用ReadToEnd 不起作用。您需要使用 proc.BeginOutputReadLine() 代替(和 proc.BeginErrorReadLine() 用于错误输出)。

但是,这些方法是异步的,因此您需要使用事件处理程序来实际获取输出。

PSI.EnableRaisingEvents = true;
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputReceivedHandler);
proc.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorReceivedHandler);

处理程序将输出/错误数据存储在事件参数的Data 属性中。

private void OutputReceivedHandler(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}

private void ErrorReceivedHandler(object sender, ErrorReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}

由于这都是异步的,因此您需要放弃 WaitForExit 调用,因为这会不必要地阻塞。如果您确实想要阻止调用,您可以使用WaitForExit,但请参阅the answer that user Greg linked in the comments 以获得不会导致缓冲区溢出的实现。

【讨论】:

  • 这个问题对于谈到上述内容的他来说可能是一个可靠的参考。 stackoverflow.com/questions/139593/…
  • @Greg 然后将问题标记为重复,而不是发布糟糕的答案
  • @Eser 我在慢动作,大脑间隔开。
  • @pushasha 当然执行一个进程并读取输出已经被回答了数百万次。 "asinus asinum fricat"
  • @pushasha BTW:我赞成你的回答
猜你喜欢
  • 2011-02-04
  • 1970-01-01
  • 2015-05-18
  • 2015-07-31
  • 1970-01-01
  • 2016-07-13
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多