命令完成后获取命令提示符窗口内容

Lia*_*mGu 2 c# cmd winforms

我想在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;
}
Run Code Online (Sandbox Code Playgroud)

而且它有效.它抓取至少一些输出并显示它,但ping本身不执行 - 或者至少这是我假设给定下面的输出并且命令提示窗口闪烁一小段时间.

输出:

Microsoft Windows [版本6.1.7601]版权所有(c)2009 Microsoft Corporation.版权所有.

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

非常感谢任何帮助.

Bal*_*i C 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; 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述