天天看點

C#隐式執行CMD指令

本文實作C#隐式執行CMD功能指令。下圖是示例程式的主界面。

在指令文本框輸入DOS指令,點選“Run”button。在以下的文本框中輸出執行結果。

C#隐式執行CMD指令

以下是程式的完整代碼。

本程式沒有使用p.StandardOutput.ReadtoEnd()和p.StandardOutput.ReadLine()方法來獲得輸出,由于這些方法運作後畫面easy卡死。

而是通過調用異步方法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();