首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 執行 CMD 命令的完整實作範例

     編輯:ASP.NET 基礎

前言

在 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;
        }
    }
}

關鍵屬性說明

  • UseShellExecute = false:預設為 true,必須設為 false 才能使用 RedirectStandardInput/Output/Error。
  • RedirectStandardInput:允許程式向 cmd 送入指令。
  • RedirectStandardOutput:讓程式讀取 cmd 的標準輸出。
  • RedirectStandardError:捕捉錯誤輸出,避免例外被吞沒。
  • CreateNoWindow:避免在伺服器上彈出黑色視窗,適合無人值守環境。

注意事項與最佳實務

  1. 權限問題:ASP.NET 執行身分(通常是 IIS AppPool 身分)必須有執行對應命令的權限。
  2. 逾時處理:長時間執行的命令建議加上 p.WaitForExit(timeout) 避免阻塞請求執行緒。
  3. 資安風險:若命令參數來自使用者輸入,嚴防命令注入,務必做嚴格驗證與白名單過濾。
  4. 編碼處理:中文環境下輸出可能為 Big5/CP950,必要時指定 StandardOutput.CurrentEncoding。

擴充應用

此模式可擴充為:批次執行多條指令、呼叫 PowerShell、執行外部 .exe 並傳遞參數、非同步執行並透過 SignalR 即時回報進度等進階場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved