本文實作C#隐式執行CMD功能指令。下圖是示例程式的主界面。
在指令文本框輸入DOS指令,點選“Run”button。在以下的文本框中輸出執行結果。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5CN3UjYjRzM1M2YyEWM5ETMxEGM4YTOklDMzcTOxUWNh9CXyAzLchDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL4M3Lc9CX6MHc0RHaiojIsJye.png)
以下是程式的完整代碼。
本程式沒有使用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();