C#執行CMD命令進行相關操作,記錄一下。
/// <summary> /// 執行CMD命令 /// </summary> /// <param name="cmd">要執行的命令</param> /// <returns></returns> public static string RunCMDCommand(string cmd) { string cmdPath = "C:\\Windows\\System32\\cmd.exe"; //cmd.exe執行文件目錄 cmd = cmd.Trim().TrimEnd('&') + "&exit"; //不管命令是否成功均執行exit命令,否則當調用ReadToEnd()方法時,會處於假死狀態 string result = string.Empty; Process process = new Process(); try { //設置要啟動的執行程序 process.StartInfo.FileName = cmdPath; //是否使用操作系統shell啟動進程 process.StartInfo.UseShellExecute = false; //應用程序的輸入是否從Process.StandardInput流中讀取/是否接受來自調用程序的輸入信息 process.StartInfo.RedirectStandardInput = true; //是否將應用程序的輸出寫入Process.StandardOutput流中/是否調用程序獲取輸出信息 //置為false時StandardOutput.ReadToEnd獲取異常 process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); //向cmd窗口寫入命令 process.StandardInput.WriteLine(cmd); process.StandardInput.AutoFlush = true; //獲取cmd窗口的輸出信息 result = process.StandardOutput.ReadToEnd(); process.WaitForExit();//等待程序執行完退出進程 process.Close(); } catch(Exception ex) { //記錄錯誤日志信息 //log4net result = string.Empty; } finally { //釋放 process.Dispose(); } return result; }
調用:
string cmdStr = "***************"; //要執行的命令 string cmdResult=RunCMDCommand(cmdStr); MessageBox.Show("CMD命令處理結果:"+cmdResult);
歡迎相互交流學習!
jiayan1578@outlook.com