

public static void RunCmd(string cmd, out string output)
{
cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
using (System.Diagnostics.Process p = new System.Diagnostics.Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
p.StartInfo.CreateNoWindow = true; //不显示程序窗口
p.Start();//启动程序
//向cmd窗口写入命令
p.StandardInput.WriteLine(cmd);
p.StandardInput.AutoFlush = true;
//获取cmd窗口的输出信息
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//等待程序执行完退出进程
p.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
string cmd = @"ipconfig /flushdns";
string output = "";
try
{
RunCmd(cmd, out output);
Regex reg = new Regex("Successfully|成功");//提取执行结果正则判断是否成功
Match match = reg.Match(output);
if (match.Success)
{
MessageBox.Show("Successfully flushed the DNS Resolver Cache.", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("发生错误请重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch
{
MessageBox.Show("发生错误此功能故障", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

亲爱的:若该文章解决了您的问题,可否收藏+评论+分享呢?

文章评论 本文章有个评论