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

C# 開發 Windows Service 程序(下):Main 入口、服務安裝與部署完整流程

     編輯:關於C語言

Main 入口點邏輯

程式透過命令列參數決定執行模式:

static void Main(string[] args) {
    // 取得 InstallUtil.exe 完整路徑(與 mscorlib.dll 同目錄)
    string installUtil = Path.GetDirectoryName(typeof(string).Assembly.CodeBase.Replace("file:///", "")) + "\\InstallUtil.exe";

    foreach (string arg in Environment.GetCommandLineArgs()) {
        switch (arg.ToLower()) {
            case "/install":
                Process.Start(installUtil, Assembly.GetExecutingAssembly().Location).WaitForExit();
                return;
            case "/uninstall":
                Process.Start(installUtil, "/u " + Assembly.GetExecutingAssembly().Location).WaitForExit();
                return;
            case "/client":
                Application.Run(new frmMain()); // 啟動客戶端 GUI
                return;
            case "/debug":
                MyFileSystemWatcherService svc = new MyFileSystemWatcherService();
                svc.StartFileSystemWatching(); // 模擬 OnStart
                Thread.Sleep(Timeout.Infinite); // 保持主執行緒存活供除錯
                return;
        }
    }
    // 無辨識參數 → 服務模式
    ServiceBase.Run(new MyFileSystemWatcherService());
}

服務安裝與執行指令

// 安裝
MyWindowsService.exe /install
// 或
installutil.exe MyWindowsService.exe

// 移除
MyWindowsService.exe /uninstall
// 或
installutil.exe /u MyWindowsService.exe

// 執行客戶端
MyWindowsService.exe /client

部署注意事項

  • 服務管理器啟動程式**不帶參數**,故預設進入服務模式
  • 直接雙擊 EXE 會因缺乏 SCM 環境而報錯,必須加參數
  • .NET Framework 封裝底層 API,大幅降低服務開發門檻

小結

本課程示範以 C# 開發檔案系統監視 Windows Service,包含伺服器端監視邏輯與客戶端管理介面,展現 .NET 框架快速建構強大後台服務的能力。

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