標籤:
C#通過程式來調用cmd命令的操作
string str = Console.ReadLine();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(str + "&exit");p.StandardInput.AutoFlush = true;//p.StandardInput.WriteLine("exit");//向標準輸入寫入要執行的命令。這裡使用&是批處理命令的符號,表示前面一個命令不管是否執行成功都執行後面(exit)命令,如果不執行exit命令,後面調用ReadToEnd()方法會假死//同類的符號還有&&和||前者表示必須前一個命令執行成功才會執行後面的命令,後者表示必須前一個命令執行失敗才會執行後面的命令//擷取cmd視窗的輸出資訊string output = p.StandardOutput.ReadToEnd();//StreamReader reader = p.StandardOutput;//string line=reader.ReadLine();//while (!reader.EndOfStream)//{// str += line + " ";// line = reader.ReadLine();//}p.WaitForExit();//等待程式執行完退出進程p.Close();Console.WriteLine(output);
需要提醒注意的一個地方就是:在前面的命令執行完成後,要加exit命令,否則後面調用ReadtoEnd()命令會假死。
我在之前測試的時候沒有加exit命令,輸入其他命令後視窗就假死了,也沒有輸出內容。
對於執行cmd命令時如何以管理員身份運行,可以看我上一篇文章: C#如何以管理員身份運行程式 - 酷小孩 - 部落格園
另一種C#調用cmd命令的方法,不過這種方法在執行時會“閃一下” 黑視窗,各位在使用時可以按喜好來調用。
/// <summary>/// 運行cmd命令/// 會顯示命令視窗/// </summary>/// <param name="cmdExe">指定應用程式的完整路徑</param>/// <param name="cmdStr">執行命令列參數</param>static bool RunCmd(string cmdExe, string cmdStr){ bool result = false; try { using (Process myPro = new Process()) { //指定啟動進程是調用的應用程式和命令列參數 ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr); myPro.StartInfo = psi; myPro.Start(); myPro.WaitForExit(); result = true; } } catch { } return result;}/// <summary>/// 運行cmd命令/// 不顯示命令視窗/// </summary>/// <param name="cmdExe">指定應用程式的完整路徑</param>/// <param name="cmdStr">執行命令列參數</param>static bool RunCmd2(string cmdExe, string cmdStr){ bool result = false; try { using (Process myPro = new Process()) { myPro.StartInfo.FileName = "cmd.exe"; myPro.StartInfo.UseShellExecute = false; myPro.StartInfo.RedirectStandardInput = true; myPro.StartInfo.RedirectStandardOutput = true; myPro.StartInfo.RedirectStandardError = true; myPro.StartInfo.CreateNoWindow = true; myPro.Start(); //如果調用程式路徑中有空格時,cmd命令執行失敗,可以用雙引號括起來 ,在這裡兩個引號表示一個引號(轉義) string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit"); myPro.StandardInput.WriteLine(str); myPro.StandardInput.AutoFlush = true; myPro.WaitForExit(); result = true; } } catch { } return result;}
C#程式調用cmd執行命令(轉)