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

标签 c# winforms cmd

我希望在 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 [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

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

非常感谢任何帮助。

最佳答案

这样就可以了

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

关于c# - 命令完成后获取命令提示符窗口内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11608959/

相关文章:

.net - 如何在 Windows 窗体设置文件中存储枚举值?

c# - DataGridView 的 RowPrePaint 中的 PaintParts 不起作用?

batch-file - 在批处理文件的 cmd.exe 标题栏中显示 "title"?

c# - 随机生成3x3x3 "block"大结构

c# - 为什么 System.Net.IPAddress 使用签名类型?

c# - 反序列化接口(interface)集合时,使用自定义转换器从以前的数据模型反序列化 JSON 失败

c# - 在启动任务栏上覆盖全屏 C# 应用程序

c# - 如何从另一个 MDI 子窗体关闭特定的 MDI 子窗体

ExtJS 主题集中化

batch-file - 如何使用 ffmpeg 批量转换文件?