1.简单调用外部程序文件(exe文件,批处理等),只需下面一行代码即可
System.Diagnostics.Process.Start(“应用程序文件.exe”);
2.如果要等待调用外部程序执行完毕才执行下面代码,只需要在后面加上WaitForExit()方法
System.Diagnostics.Process.Start(应用程序文件全路径).WaitForExit();
3.另一种方法:使用实例化方法不使用静态方法
1 Process process = new Process();
2 process.StartInfo = new ProcessStartInfo(路径, 参数);
3 process.Start();
4 process.WaitForExit();
5 MessageBox.Show("处理已经完成!", "提示");
4.调用cmd.exe执行命令并获取返回结果 受教于C#程序调用cmd执行命令
RunCmd("ipconfig")//运行cmd命令 并获取返回结果
string RunCmd(string cmd)
{
try
{
Process pro = new Process();
pro.StartInfo.FileName = @"cmd.exe";
pro.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
pro.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
pro.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
pro.StartInfo.RedirectStandardError = true; //重定向标准错误输出
pro.StartInfo.CreateNoWindow = true; //不显示程序窗口
pro.Start();
pro.StandardInput.WriteLine($"{cmd}&exit");
pro.StandardInput.AutoFlush = true;
string result = pro.StandardOutput.ReadToEnd();
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.AppendText(result);
richTextBox1.AppendText("".PadLeft(30, '='));
pro.WaitForExit();
pro.Close();
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return string.Empty;
}
}