How to Create a Windows Service In C#?

 Admin   
199 View    Jan 20 2020 11:12PM

Windows Services are non UI programming applications that run out of sight. Windows administrations are generally begins when a working framework boots and booked to run out of sight to execute a few errands. Windows administrations can likewise be begun naturally or physically. You can likewise physically respite, stop and restart Windows administrations.

Windows administration is a PC program that runs out of sight to execute a few assignments. A few instances of Windows administrations are auto update of Windows, browse messages, print records, SQL Server specialist, document and organizer examining and ordering, etc. In the event that you open your Task Manager and snap on Services tab, you will see many administrations running on your machine. You can likewise observe the statuses of these administrations. A few administrations are running, some have delayed, and some have halted. You can begin, stop, and interruption a help from here by right snap on the administration.

 

 

You may also find all services running on your machine in the following ways:

  • Go to Control Panel select “Services” inside “Administrative Tools”.
  • Open Run window (Window + R) and type services.msc and press ENTER.

How to create a Windows service in C#?

 

Let's create a Windows Service in C# using Visual Studio. 

 

Step 1

 

Open Visual Studio, go to File > New and select Project. Now select new project from Dialog box and select “Window Service” and click on OK button.

 

Step 2

Go to Visual C# -> ”Windows Desktop” -> ”Windows Service” and give an appropriate name and then click OK

 

 

Once you click OK button the below screen will appear, which is your service

  

 

Step 3

Right click on the blank area and select “Add Installer”

 

 

How to Add an Installer to a Windows Service

 

Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.

 

After Adding Installer, Project Installer will add in your project and ProjectInstakker.cs file will be open. Don’t forgot to save everything (by pressing ctrl + shift + s key)

 

Solution Explore looks like this:

windows service

 

Step 4

Right click on blank area and select “View Code”

 

Step 5


Its has Construtor which contains InitializeComponent method:

 

The InitializeComponent method contains the logic which create and initializes the user interface objects dragged on the form surface and provided the Property Grid of Form Designer.

 

Very important: Don't ever try to call any method before the call of InitializeComponent method.

 

 

 

Step 6

Select InitializeComponent method and press F12 key to go definition

 

 

Step 7

Now add the below line:

 

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

 

You also can add description and display service name (optionally).

 

·  this.serviceInstaller1.Description = "My First Service demo";  

·  this.serviceInstaller1.DisplayName = "MyFirstService.Demo"; 

 

 

Step 8

In this step, we will implement a timer, and code to call the service at a given time. We will create a text file and write current time in the text file using the service. 

 

 

 

 

Service1.cs class 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.ServiceProcess;  
  9. using System.Text;  
  10. using System.Threading.Tasks;  
  11. using System.Timers;  
  12. namespace MyFirstService {  
  13.     public partial class Service1: ServiceBase {  
  14.         Timer timer = new Timer(); // name space(using System.Timers;)  
  15.         public Service1() {  
  16.             InitializeComponent();  
  17.         }  
  18.         protected override void OnStart(string[] args) {  
  19.             WriteToFile("Service is started at " + DateTime.Now);  
  20.             timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
  21.             timer.Interval = 5000; //number in milisecinds  
  22.             timer.Enabled = true;  
  23.         }  
  24.         protected override void OnStop() {  
  25.             WriteToFile("Service is stopped at " + DateTime.Now);  
  26.         }  
  27.         private void OnElapsedTime(object source, ElapsedEventArgs e) {  
  28.             WriteToFile("Service is recall at " + DateTime.Now);  
  29.         }  
  30.         public void WriteToFile(string Message) {  
  31.             string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
  32.             if (!Directory.Exists(path)) {  
  33.                 Directory.CreateDirectory(path);  
  34.             }  
  35.             string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";  
  36.             if (!File.Exists(filepath)) {  
  37.                 // Create a file to write to.   
  38.                 using(StreamWriter sw = File.CreateText(filepath)) {  
  39.                     sw.WriteLine(Message);  
  40.                 }  
  41.             } else {  
  42.                 using(StreamWriter sw = File.AppendText(filepath)) {  
  43.                     sw.WriteLine(Message);  
  44.                 }  
  45.             }  
  46.         }  
  47.     }  
  48. }  

 

Code explanation - the above code will call service every 5 seconds and create a folder if none exists and write our message.

 

Step 9. Rebuild your application.

 

Right click on your project or solution and select Rebuild.

 

 

Step 10

Search “command Prompt” and run as administrator

windows service

 

Step 11

Fire the below command in the command prompt and press ENTER.

 

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 

 

 

windows service

 

Step 12

Now Go to your project source folder > bin > Debug and copy the full path of your Windows Service exe file

 

 

 

Installing a Windows Service

Open command prompt and fire the below command and press ENTER.

  

Syntax

InstallUtil.exe + Your copied path + \your service name + .exe

 

Our path

InstallUtil.exe

C:\Users\Mindspark\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

 

 

 

Check status of a Windows Service


Open services by following the below steps:

  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.

 

windows service

 

windows service

 

You may notice that the Windows service is running. 

windows service

Check Windows Service Output 

 

The service will create a text file with the following text in it. 

 

 

Log folder will be created in your bin folder.

 

Uninstalling a Windows Service



If you want to uninstall your service, fire the below command.

  1. Syntax InstallUtil.exe -u + Your copied path + \your service name + .exe
  2. Our path InstallUtil.exe -u C:\Users\csharpmonster\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe