1 string str = Console.ReadLine(); 2 3 System.Diagnostics.Process p = new System.Diagnostics.Process(); 4 p.StartInfo.FileName = "cmd.exe"; 5 p.StartInfo.UseShellExecute = false; //是否使用操做系統shell啓動 6 p.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息 7 p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息 8 p.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出 9 p.StartInfo.CreateNoWindow = true;//不顯示程序窗口 10 p.Start();//啓動程序 11 12 //向cmd窗口發送輸入信息 13 p.StandardInput.WriteLine(str + "&exit"); 14 15 p.StandardInput.AutoFlush = true; 16 //p.StandardInput.WriteLine("exit"); 17 //向標準輸入寫入要執行的命令。這裏使用&是批處理命令的符號,表示前面一個命令無論是否執行成功都執行後面(exit)命令,若是不執行exit命令,後面調用ReadToEnd()方法會假死 18 //同類的符號還有&&和||前者表示必須前一個命令執行成功纔會執行後面的命令,後者表示必須前一個命令執行失敗纔會執行後面的命令 19 20 21 22 //獲取cmd窗口的輸出信息 23 string output = p.StandardOutput.ReadToEnd(); 24 25 //StreamReader reader = p.StandardOutput; 26 //string line=reader.ReadLine(); 27 //while (!reader.EndOfStream) 28 //{ 29 // str += line + " "; 30 // line = reader.ReadLine(); 31 //} 32 33 p.WaitForExit();//等待程序執行完退出進程 34 p.Close(); 35 36 37 Console.WriteLine(output);
須要提醒注意的一個地方就是:在前面的命令執行完成後,要加exit命令,不然後面調用ReadtoEnd()命令會假死。html
我在以前測試的時候沒有加exit命令,輸入其餘命令後窗口就假死了,也沒有輸出內容。shell
對於執行cmd命令時如何以管理員身份運行,能夠看我上一篇文章: C#如何以管理員身份運行程序 - 酷小孩 - 博客園測試
2014-7-28 新增:spa
另外一種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; }
做者:酷小孩 命令行