Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีติดตั้ง Windows Service ผ่าน Command Prompt ใน C#

ขั้นตอนที่ 1: สร้าง Windows Service Application

สร้าง Project ใหม่แบบ Windows Service Application ใน Visual Studio

ขั้นตอนที่ 2: เพิ่ม Installer

สำหรับการรัน Windows Service ต้องติดตั้ง Installer ซึ่งจะลงทะเบียนกับ Service Control Manager คลิกขวาที่ Service1.cs [Design] แล้วเลือก Add Installer

ขั้นตอนที่ 3: กำหนดค่า ProjectInstaller

คลิกขวาที่ ProjectInstaller.cs [Design] เลือก View Code กด F12 ไปที่ InitializeComponent เพื่อเพิ่ม Service Name และ Description

private void InitializeComponent() {
    this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    
    // serviceProcessInstaller1
    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
    this.serviceProcessInstaller1.Password = null;
    this.serviceProcessInstaller1.Username = null;
    
    // serviceInstaller1
    this.serviceInstaller1.Description = "My Demo Service";
    this.serviceInstaller1.ServiceName = "DemoService";
    
    // ProjectInstaller
    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
        this.serviceProcessInstaller1,
        this.serviceInstaller1
    });
}

ขั้นตอนที่ 4: เพิ่ม Logic เขียน Log

เพิ่มโค้ดใน Service1.cs เพื่อเขียน Log ลง Text File

using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;

namespace DemoWindowsService {
    public partial class Service1 : ServiceBase {
        Timer timer = new Timer();
        
        public Service1() {
            InitializeComponent();
        }
        
        protected override void OnStart(string[] args) {
            WriteToFile("Service started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000;
            timer.Enabled = true;
        }
        
        protected override void OnStop() {
            WriteToFile("Service stopped at " + DateTime.Now);
        }
        
        private void OnElapsedTime(object source, ElapsedEventArgs e) {
            WriteToFile("Service recall at " + DateTime.Now);
        }
        
        public void WriteToFile(string Message) {
            string path = @"D:\Demo";
            if (!Directory.Exists(path)) {
                Directory.CreateDirectory(path);
            }
            string filepath = @"D:\Demo\Log.txt";
            if (!File.Exists(filepath)) {
                using (StreamWriter sw = File.CreateText(filepath)) {
                    sw.WriteLine(Message);
                }
            } else {
                using (StreamWriter sw = File.AppendText(filepath)) {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

ขั้นตอนที่ 5: ติดตั้งผ่าน Command Prompt (Run as Administrator)

  1. เปิด Command Prompt แบบ Administrator
  2. เข้าไปที่ Folder .NET Framework:
    cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
    
  3. รัน InstallUtil.exe พร้อม Path ของ Service exe:
    InstallUtil.exe "C:\Path\To\Your\Service\bin\Debug\DemoWindowsService.exe"
    

การตรวจสอบ

  1. เปิด Services (services.msc) จาก Start Menu
  2. ค้นหา "DemoService" หรือชื่อที่ตั้งไว้
  3. ตรวจสอบ Status ว่าเป็น Running
  4. ตรวจสอบ Log File ที่ D:\Demo\Log.txt

คำสั่งที่มีประโยชน์

// Uninstall Service
InstallUtil.exe /u "C:\Path\To\Service.exe"

// Start Service
net start DemoService

// Stop Service
net stop DemoService

// ดูรายการ Services
sc query type= service state= all

ข้อควรระวัง

  • ต้อง Run Command Prompt แบบ Administrator
  • Path ต้องถูกต้อง และ Escape ให้ถูกต้องถ้ามี Space
  • Service Account (LocalService, LocalSystem, NetworkService, User) ต้องมี Permission เพียงพอ
  • ใน .NET Core / .NET 5+ ให้ใช้ dotnet publish แล้วค่อย InstallUtil กับ exe ที่ได้