Command prompt output being read as empty string

空扰寡人 提交于 2019-12-17 19:52:52

问题


I'm trying to execute command prompt commands and read the output in C#. This is my code:

ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
cmdInfo.CreateNoWindow = true;
cmdInfo.RedirectStandardOutput = true;
cmdInfo.UseShellExecute = false;

Process cmd = new Process();
cmd.StartInfo = cmdInfo;
cmd.Start();
string result = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
cmd.Close();
return result;

It works most of the time, but sometimes result="" when that's impossible for the command I'm using (for example, route add should give output on success or failure). Any ideas? I was wondering if maybe I'd created a race condition between the process and the ReadToEnd call?


回答1:


Not all output is written to StandardOutput; many applications will instead write to StandardError if something goes wrong. You would have to read from both to get all of the output.

As long as the application never blocks for input, it should be safe to call ReadToEnd() on both output streams to get all of the output. A safer option, however, is to hook up an event to the OutputDataReceived and ErrorDataReceived events. You can attach lambda expression to these that close over local variables to make things pretty simple:

var output = new StringBuilder();
var error = new StringBuilder();

cmd.OutputDataReceived += (o, e) => output.Append(e.Data);
cmd.ErrorDataReceived += (o, e) => error.Append(e.Data);

cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
cmd.WaitForExit();


来源:https://stackoverflow.com/questions/11060019/command-prompt-output-being-read-as-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!