本文實現了C#隱式運行CMD命令的功能。下圖是實例程序的主畫面。在命令文本框輸入DOS命令,點擊“Run”按鈕,在下面的文本框中輸出運行結果。
下面是程序的完整代碼。本程序沒有使用p.StandardOutput.ReadtoEnd()和p.StandardOutput.ReadLine()方法來獲得輸出,因為這些方法執行后畫面容易卡死。而是通過調用異步方法BeginOutputReadLine來獲取輸出,並在事件p.OutputDataReceived的事件處理方法中來處理結果。
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace RunDosCommandForm { publicpartialclassForm1 : Form { publicForm1() { InitializeComponent(); } private void button1_Click(object sender, EventArgse) { ExcuteDosCommand(textBox1.Text); } private void ExcuteDosCommand(string cmd) { try { Process p = newProcess(); p.StartInfo.FileName = "cmd"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += new DataReceivedEventHandler(sortProcess_OutputDataReceived); p.Start(); StreamWriter cmdWriter = p.StandardInput; p.BeginOutputReadLine(); if (!String.IsNullOrEmpty(cmd)) { cmdWriter.WriteLine(cmd); } cmdWriter.Close(); p.WaitForExit(); p.Close(); } catch(Exception ex) { MessageBox.Show("執行命令失敗,請檢查輸入的命令是否正確!"); } } private void sortProcess_OutputDataReceived(object sender,DataReceivedEventArgs e) { if(!String.IsNullOrEmpty(e.Data)) { this.BeginInvoke(newAction(() => { this.listBox1.Items.Add(e.Data);})); } } } }
我們還可以將需要運行的CMD命令保存為BAT文件,再使用Process類來執行。
Process p = new Process();//設定調用的程序名,不是系統目錄的需要完整路徑 p.StartInfo.FileName = "cmd.bat";//傳入執行參數 p.StartInfo.Arguments = ""; p.StartInfo.UseShellExecute = false;//是否重定向標准輸入 p.StartInfo.RedirectStandardInput = false;//是否重定向標准轉出 p.StartInfo.RedirectStandardOutput = false;//是否重定向錯誤 p.StartInfo.RedirectStandardError = false;//執行時是不是顯示窗口 p.StartInfo.CreateNoWindow = true;//啟動 p.Start(); p.WaitForExit(); p.Close();