2012-07-23 128 views
2

我期待在C#中完成命令后获取命令提示符窗口的内容。命令完成后获取命令提示符窗口内容

具体而言,在这种情况下,我从按钮单击发出ping命令,并希望在文本框中显示输出。

我目前使用的代码是:

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe"); 
startInfo.UseShellExecute = false; 
startInfo.RedirectStandardOutput = true; 
startInfo.RedirectStandardError = true; 
startInfo.Arguments = "ping 192.168.1.254"; 
Process pingIt = Process.Start(startInfo); 
string errors = pingIt.StandardError.ReadToEnd(); 
string output = pingIt.StandardOutput.ReadToEnd(); 

txtLog.Text = ""; 
if (errors != "") 
{ 
    txtLog.Text = errors; 
} 
else 
{ 
    txtLog.Text = output; 
} 

而且它的工作原理有点。它抓取至少一些输出并显示它,但ping本身不执行 - 或者至少这是我假定给出的输出如下,命令提示符窗口闪烁一会儿。

输出:

的Microsoft Windows [版本6.1.7601]版权所有(C)2009年微软 公司。版权所有。

C:\结帐\ PingUtility \ PingUtility \ BIN \调试>

任何援助不胜感激。

回答

6

这应该这样做

ProcessStartInfo info = new ProcessStartInfo(); 
info.Arguments = "/C ping 127.0.0.1"; 
info.WindowStyle = ProcessWindowStyle.Hidden; 
info.CreateNoWindow = true; 
info.FileName = "cmd.exe"; 
info.UseShellExecute = false; 
info.RedirectStandardOutput = true; 
using (Process process = Process.Start(info)) 
{ 
    using (StreamReader reader = process.StandardOutput) 
    { 
     string result = reader.ReadToEnd(); 
     textBox1.Text += result; 
    } 
} 

输出

enter image description here

+0

啊,本来是完美的!我至少有点正确。谢谢! – LiamGu 2012-07-23 08:48:19