我希望在 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;
}
}
输出
关于c# - 命令完成后获取命令提示符窗口内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11608959/