无法从cmd.exe执行中获取输出

3
代码如下:
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 中得到 "The system cannot find the file specified",因为 "123" 是一个不存在的文件路径。但实际上 output 是一个空字符串。为什么会这样,我该如何获取输出结果?

仍然有疑问,请看下面的评论... - yeeen
1个回答

5
您期望看到的消息将出现在StandardError而不是StandardOutput中。

为什么有时候期望的错误信息会出现在输出中呢?例如,如果我没有为目标路径放置开头和结尾的引号,MOVE命令就会出现这种情况。"命令语法不正确"的消息会出现在“StandardOutput”而不是“StandardError”,而“StandardError”为空。 - yeeen
您正在使用命令行处理器。用户误输入命令可能太常见了,不能称之为错误。不要使用cmd.exe来执行此操作,而应改用System.IO命名空间中的类。 - Hans Passant
@yeeen - 微软在编写执行命令的代码时存在不一致性。 - Andrew Cooper
@Hans,你是指使用“System.IO”命名空间中的类吗? - yeeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接