【发布时间】: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);
【问题讨论】:
-
我正要发布答案,但不幸的是,它因无效的主要原因而关闭。构造函数中指定的参数被
Arguments属性覆盖。所以你实际调用的是cmd.exe /c而不是cmd.exe {command},它不会输出任何东西。参考:github.com/Microsoft/referencesource/blob/master/System/… 和 github.com/Microsoft/referencesource/blob/master/System/…
标签: c# cmd streamreader