gpt4 book ai didi

c# - 如何将cmd命令输出放入标签中

转载 作者:行者123 更新时间:2023-12-02 22:55:14 25 4
gpt4 key购买 nike

我编写了从 C# 表单应用程序运行 cmd 命令的代码。现在我想将cmd的输出获取到winform中的标签。我编写了一段代码。但它给了我以下错误

Screenshot of the Error

System.dll 中发生“System.InvalidOperationException”类型的未处理异常其他信息:StandardOut 尚未重定向或流程尚未开始。

如何解决?这是我的原始代码。

private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startiNFO = new System.Diagnostics.ProcessStartInfo();

startiNFO.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startiNFO.FileName = "cmd.exe";
startiNFO.Arguments = "/C ipconfig";
startiNFO.UseShellExecute = false;

process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;

process.StartInfo = startiNFO;

process.Start();

string outp = process.StandardOutput.ReadToEnd();
process.WaitForExit();

MessageBox.Show(outp);
}

最佳答案

而不是process.WaitForExit();做这样的事情

函数的完整代码如下所示

private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C ipconfig";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
while(!process.HasExited)
{
q += process.StandardOutput.ReadToEnd();
}
label1.text = q;
MessageBox.Show(q);
}

关于c# - 如何将cmd命令输出放入标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41355117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com