本篇介紹 C#控制命令提示字元(cmd)輸入Dos指令 ,透過C#程式透過Process來操作終端機可以應用在許多地方,包含:控制電腦複製檔案、檢測網路連線、執行程式…等,而這方法在程式碼的寫法上相對較簡單與直觀,就如同直接在電腦上執行cmd.exe並輸入Dos指令的做法大同小異,如果您想知道程式碼該如何撰寫,就趕緊往下看C#的教學範例吧。
C#控制命令提示字元(cmd)輸入Dos指令 | 程式碼教學
首先使用前需要加入Process的類別
- using System.Diagnostics;
ProcessStarInfo的初始設置
- ProcessStarInfo cmd = new System.Diagnostics.ProcessStartInfo(“cmd.exe”);
- cmd.RedirectStandardInput = true; /* 重定向輸入流 */
- cmd.RedirectStandardOutput = true; /* 重定向輸出流 */
- cmd.RedirectStandardError = true; /* 重定向錯誤流 */
- cmd.UseShellExecute = false; /* 是否使用外殼程式 */
啟動(或重啟) ProcessStartInfo 所指定的進程資源並將其關聯。
- Process console = Process.Start(“填入ProcessStarInfo的名稱“);
利用WriteLine將Dos指令輸入到命令提示字元中。
- console.StandardInput.WriteLine(“填入Dos指令“);
取得DOS指令輸入後返回的結果並將其存在output字串內。
- string output = console.StandardOutputReadToEnd();
C# 範例程式
using System.Diagnostics namespace WindowsFormsApplication1
{
public partial class Form1:Form
{
public Form1()
{
initializeComponent();
}
private void button1_Click(object snedr.EventArgs e)
{
ProcessStarInfo cmd = new System.Diagnostics.ProcessStartInfo("cmd.exe");
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.UseShellExecute = false;
/* 將命令提示字元cmd.exe程式啟動並執行 */
Process console = Process.Start("cmd");
/* 在命令提示字元中輸入 "C:" */
console.StandardInput.WriteLine("C:");
/* 在命令提示字元中輸入 "cd\\" */
console.StandardInput.WriteLine("cd\\");
/* 在命令提示字元中輸入 "exit" */
console.StandardInput.WriteLine("exit");
/* 獲取輸入指令後回傳的結果 */
string output = console.StandardOutputReadToEnd();
/* 關閉cmd程式 */
console.Close();
/* 在messageBox 上顯示輸出結果 */
MessageBox.Show(output);
}
}
}