1단계 -
새 Windows 서비스 응용 프로그램을 만듭니다.

2단계 -
Windows 서비스를 실행하려면 Service Control Manager에 등록하는 Installer를 설치해야 합니다. Service1.cs[Design] 및 AddInstaller를 마우스 오른쪽 버튼으로 클릭합니다.


3단계 -
ProjectInstaller.cs [Design]를 마우스 오른쪽 버튼으로 클릭하고 보기 코드를 선택합니다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;
namespace DemoWindowsService{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer{
public ProjectInstaller(){
InitializeComponent();
}
}
} F12 키를 누르고 InitializeComponent 클래스의 구현으로 이동합니다. 설치하는 동안 Windows 서비스의 이름이 될 서비스 이름과 설명을 추가합니다.
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단계 -
이제 Service1.cs 클래스의 텍스트 파일에 로그 데이터를 작성하는 로직을 아래에 추가해 보겠습니다.
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단계(설치) -
이제 명령 프롬프트를 사용하여 Windows 서비스를 설치합니다. 관리자 권한으로 명령 프롬프트를 열고 아래 명령을 입력하세요.
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Windows 서비스 exe 파일이 있는 폴더를 열고 아래 명령을 실행합니다.
InstallUtil.exe C:\Users\[UserName] source\repos\DemoWindowsService\DemoWindowsService\bin\Debug\ DemoWindowsService.exe


이제 Windows 응용 프로그램 메뉴에서 서비스를 엽니다.


Windows 서비스가 설치되고 예상대로 실행되는 것을 볼 수 있습니다.
아래 출력은 서비스가 실행 중이며 예상대로 로그를 텍스트 파일에 연결하는 것을 보여줍니다.
