【问题标题】:Cannot get output from cmd.exe execution无法从 cmd.exe 执行中获取输出
【发布时间】:2011-09-06 20:16:57
【问题描述】:

代码如下:

ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c" + command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Arguments = arguments;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;

Process process = Process.start(startInfo);
StreamReader srOutput = process.StandardOutput;
string output = srOutput.ReadToEnd();

命令是rmdir /s /q 123

我希望在变量output 中得到“系统找不到指定的文件”,因为“123”是一个不存在的文件路径。但是output 是一个空字符串。为什么以及如何获取输出?

【问题讨论】:

  • 仍有疑问,见下方评论...

标签: c# process cmd


【解决方案1】:

您希望看到的消息将是StandardError,而不是StandardOutput

【讨论】:

  • 为什么有时预期的错误消息会出现在输出中?例如 MOVE 命令,如果我没有为目标路径放置打开和关闭的逗号。 “命令不正确时的语法”消息在“StandardOutput”而不是“StandardError”中,并且“StandardError”为空。
  • 您正在使用命令行处理器。让用户错误输入命令可能太常见了,不能称之为错误。只是不要使用 cmd.exe 来执行此操作,而是使用 System.IO 命名空间中的类。
  • @yeeen - 只是微软在编写执行命令的代码时不一致。
  • @Hans “使用 System.IO 命名空间中的类”是什么意思?
猜你喜欢
  • 2021-09-22
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2017-09-03
  • 2020-08-18
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多