在windows環境下,命令行程序為cmd.exe,是一個32位的命令行程序,微軟Windows系統基於Windows上的命令解釋程序,類似於微軟的DOS操作系統。輸入一些命令,cmd.exe可以執行,比如輸入shutdown -s就會在30秒后關機。總之,它非常有用。打開方法:開始-所有程序-附件 或 開始-尋找-輸入:cmd/cmd.exe 回車。它也可以執行BAT文件。
下面介紹使用C#程序調用cmd執行命令:
代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Diagnostics; 7 8 namespace CmdDemo 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 Console.WriteLine("請輸入要執行的命令:"); 15 string strInput = Console.ReadLine(); 16 Process p = new Process(); 17 //設置要啟動的應用程序 18 p.StartInfo.FileName = "cmd.exe"; 19 //是否使用操作系統shell啟動 20 p.StartInfo.UseShellExecute = false; 21 // 接受來自調用程序的輸入信息 22 p.StartInfo.RedirectStandardInput = true; 23 //輸出信息 24 p.StartInfo.RedirectStandardOutput = true; 25 // 輸出錯誤 26 p.StartInfo.RedirectStandardError = true; 27 //不顯示程序窗口 28 p.StartInfo.CreateNoWindow = true; 29 //啟動程序 30 p.Start(); 31 32 //向cmd窗口發送輸入信息 33 p.StandardInput.WriteLine(strInput+"&exit"); 34 35 p.StandardInput.AutoFlush=true; 36 37 //獲取輸出信息 38 string strOuput = p.StandardOutput.ReadToEnd(); 39 //等待程序執行完退出進程 40 p.WaitForExit(); 41 p.Close(); 42 43 Console.WriteLine(strOuput); 44 45 Console.ReadKey(); 46 } 47 } 48 }
運行效果:
應用:使用C#程序調用cmd命令生成WCF服務的客戶端調用文件
設計界面:
代碼如下:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Diagnostics; 11 12 namespace ExecuteCMD 13 { 14 public partial class FrmMain : Form 15 { 16 public FrmMain() 17 { 18 InitializeComponent(); 19 } 20 21 private void btn_Create_Click(object sender, EventArgs e) 22 { 23 try 24 { 25 //創建一個進程 26 Process p = new Process(); 27 p.StartInfo.FileName = "cmd.exe"; 28 p.StartInfo.UseShellExecute = false;//是否使用操作系統shell啟動 29 p.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息 30 p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息 31 p.StartInfo.RedirectStandardError = true;//重定向標准錯誤輸出 32 p.StartInfo.CreateNoWindow = true;//不顯示程序窗口 33 p.Start();//啟動程序 34 35 string strCMD = "\"" + @"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\SvcUtil.exe" + "\" " + this.txt_URL.Text.ToString().Trim() 36 + " /r:"+"\""+@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.dll" +"\""+ " /syncOnly"; 37 //向cmd窗口發送輸入信息 38 p.StandardInput.WriteLine(strCMD + "&exit"); 39 40 p.StandardInput.AutoFlush = true; 41 42 //獲取cmd窗口的輸出信息 43 string output = p.StandardOutput.ReadToEnd(); 44 //等待程序執行完退出進程 45 p.WaitForExit(); 46 p.Close(); 47 48 49 MessageBox.Show(output); 50 Console.WriteLine(output); 51 } 52 catch (Exception ex) 53 { 54 MessageBox.Show(ex.Message + "\r\n跟蹤;" + ex.StackTrace); 55 } 56 } 57 } 58 }
點擊創建按鈕,會在bin\Debug目錄下面生成對於的cs文件