命令提示符下输出被读为空字符串 [英] Command prompt output being read as empty string

查看:130
本文介绍了命令提示符下输出被读为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行命令提示符下命令和读取C#中的输出。这是我的代码:

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;



它工作的大部分时间,但有时会造成=当该命令是不可能的我中号使用(例如,路由添加应该给出成功或失败输出)。有任何想法吗?如果我也许会创造过程和ReadToEnd的调用之间的竞争条件我想知道?

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?

推荐答案

并非所有的输出写入到StandardOutput;如果出现问题许多应用程序反而会写信给StandardError的。你必须从两个读来获得所有的输出。

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.

只要应用程序从不为输入块,它应该是安全地调用 ReadToEnd的()在两个输出流来获得所有的输出。更安全的选择,然而,挂钩事件的 OutputDataReceived ErrorDataReceived 事件。您可以将lambda表达式这是接近了局部变量来使事情很简单:

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();

这篇关于命令提示符下输出被读为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆