问题
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