在 ASP.NET 開發中,有時需要在伺服器端執行系統指令(如 ping、批次檔、外部程式等)。本文提供一個完整的範例,示範如何使用 System.Diagnostics.Process 類別啟動 cmd.exe、重導向標準輸入/輸出/錯誤流,並取得命令執行結果。
using System;
using System.Diagnostics;
using System.Web.UI;
namespace WebForm
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 執行 ping 指令並將結果寫入頁面
Response.Write(ExeCommand("ping www.126.com"));
}
///
/// 執行 CMD 命令並回傳輸出結果
///
public string ExeCommand(string commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; // 必須為 false 才能重導向流
p.StartInfo.RedirectStandardInput = true; // 重導向標準輸入
p.StartInfo.RedirectStandardOutput = true; // 重導向標準輸出
p.StartInfo.RedirectStandardError = true; // 重導向標準錯誤
p.StartInfo.CreateNoWindow = true; // 不建立視窗
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText); // 寫入要執行的命令
p.StandardInput.WriteLine("exit"); // 送出 exit 結束 cmd
strOutput = p.StandardOutput.ReadToEnd(); // 讀取完整輸出
p.WaitForExit(); // 等待執行結束
p.Close();
}
catch (Exception ex)
{
strOutput = ex.Message; // 發生例外時回傳錯誤訊息
}
return strOutput;
}
}
}
p.WaitForExit(timeout) 避免阻塞請求執行緒。StandardOutput.CurrentEncoding。此模式可擴充為:批次執行多條指令、呼叫 PowerShell、執行外部 .exe 並傳遞參數、非同步執行並透過 SignalR 即時回報進度等進階場景。