011
From: 011netservice@gmail.com
Date: 2022-04-24
Subject: C# Windows Service Template

C# Windows Service

步驟

本例使用Visual Studio 2008, .Net 3.5, 其他版本也適用.
  1. 若專案名稱要命名為"ServiceBase", 則要注意避開跟System.ServiceProcess.ServiceBase名稱衝突的問題, 否則會導致專案無法載入編譯成功.
  2. 預設的Windows Service專案模板, 會新增Service1.cs繼承ServiceBase.
    先將ServiceName改為要顯示在windows服務中的名稱, 其餘的屬性則依需求設定:


    預設程式框架如下:


  3. 改寫為以下Service1.cs程式, 測試寫入EventLog、File以及錯誤處理.


  4. 預設的Windows Service專案模板, 還缺少Installer元件, 必須自行增加後, 才能以Installutil.exe安裝服務程式. 增加的方法為: 在繼承SeviceBase的元件上按右鍵, 選擇"Add Installer"如下:


    執行後會增加ProjectInstaller.cs檔案, 內含2個元件:
    1. Name=serviceProcessInstaller1 之 System.ServiceProcess.ServiceProcessInstaller, 將屬性設定如下:
      1. Description: 顯示在服務中的描述欄位, 可空白.
      2. DisplayName: 顯示在服務中的名稱, 建議空白不填. 若沒填寫, 則以ServiceName欄位值顯示.
      3. Account = LocalSystem. 必須擁有處理資源的權限.
      4. Modifiers=Internal.
      5. StartType=Manual 啟動類型手動或自動.
    2. Name=serviceInstaller1 之 System.ServiceProcess.ServiceInstaller, 將屬性設定如下:
      1. Modifiers=Internal.
      2. ServiceName=ServiceNameOnWindows. (顯示在(Windows服務)中的名稱), 也是Windows EventLog的來源欄位顯示的內容. 應該要跟System.ServiceProcess.Service.Base專案class之ServiceName一致.



安裝

  1. Windows Service的程式, 無法直接執行, 必須經過系統管理員安裝為服務以後, 才可以透過服務執行. 安裝工具為.Net提供的Installutil.exe.
    Install | Uninstall
    安裝: InstallUtil [program.exe]
    解除安裝: InstallUtil /u [program.exe]

    InstallUtil.exe檔案位置在
    C:\Windows\Microsoft.NET\Framework64\v2.0.50727\ 或
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ 中.

  2. 安裝成功以後, 可以在Windows服務中, 看到該服務:


執行服務

  1. 啟動/停止服務: 必須擁有權限才能執行.
    手動方式


    指令方式:
    Start | Stop
    net start [ServiceName]
    net stop [ServiceName]

  2. 本程式執行結果會在EventLog中留下應用程式事件紀錄:


    並且會寫入內容到輸出檔案c:\temp\ServiceTemplate.txt中:


自我安裝

改寫為以下內容後, 就可以由程式本身提供安裝或解除安裝的功能, 不需要工具程式InstallUtil.exe.
例如以下指令:
安裝: [ServiceTemplate] /i
解除: [ServiceTemplate] /u
Program.cs | Service1.cs




FAQ

  1. 如何Debug Windows service程式?
    有兩種方法:
    1. 利用Debug.[Attach to Process...]附加至處理序為服務的Process ID.
    2. 在需要debug的位置, 插入程式碼Debugger.Launch();


      當執行到這行指令時, Windows會提示選擇(Visual Studio Just-In-Time偵錯工具)如下:  (以下為Windows 10畫面)




  2. 如何解除安裝已經找不到exe的服務 ?
    透過sc.exe刪除, 例如: sc delete "service name in windows"


Log:
Date Author Description
2017-02-01 Honda copy from luckstat document.
011