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;
}
}