【问题标题】:Get Command Prompt Window Content After Command Completion命令完成后获取命令提示符窗口内容
【发布时间】:2012-07-21 11:28:19
【问题描述】:

我希望在 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 Microsoft 公司。保留所有权利。

C:\Checkout\PingUtility\PingUtility\bin\Debug>

非常感谢任何帮助。

【问题讨论】:

    标签: c# winforms cmd


    【解决方案1】:

    应该这样做

    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; 
        } 
    } 
    

    输出

    【讨论】:

    • 啊,太完美了!我至少有点沿着正确的路线。谢谢!
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多