標籤:process c#運行cmd命令
本文實現了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(); } privatevoidbutton1_Click(object sender, EventArgse) { ExcuteDosCommand(textBox1.Text); } privatevoidExcuteDosCommand(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 += newDataReceivedEventHandler(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("執行命令失敗,請檢查輸入的命令是否正確!"); } } privatevoidsortProcess_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();
C#隱式運CMD命令