In Focus

Create Windows Services In C#

Here I’m going to explain Windows Services in the c# .Net. Introduction of Windows Services, How to create Windows Services in the c# .Net.

Here I’m going to explain Windows Services in C# .Net.
  • Introduction of Windows Services.
  • How to create Windows Services in C# .Net.


Windows Services normally start when the OS boots. Windows Service is running an application in the background. Windows Services executes applications in its own session. It either starts automatically or we can also manually pause, stop and restart it.

Windows Service

Windows service is a computer program, which will run in the background.
You can find services 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 Windows service

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.
windows service
Step 2

Go to Visual C# -> ”Windows Desktop” -> ”Windows Service” and give an appropriate name and then click OK
windows service 
Once you click OK button the below screen will appear, which is your service
windows service 

Step 3

Right click on the blank area and select “Add Installer”
Adding Installers to the Service
Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.
windows service 
After Adding Installer, ProjectInstaller will add in your project and ProjectInstakker.cs file will be open. Don’t forgot to save everything (by pressing ctrl + shift + s key)
windows service 
Solution Explore looks like this,

windows service 
Step 4

Right click on blank area and select “View Code”
windows service
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.
windows service 
Step 6

Select InitializeComponent method and press F12 key to go definition
windows service 
Step 7

Now add the below line while installing service
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
You also can add description and display service name (optionally).
  1. this.serviceInstaller1.Description = "My First Service demo";  
  2. this.serviceInstaller1.DisplayName = "MyFirstService.Demo";  
windows service
Step 8

In this step we will implement timer, and code to call service at a given time. We will create a simple write in text file.
windows 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.

windows service 
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 full path of Windows Service exe file
windows service
windows service
Step 13

Open command prompt and fire the below command and press enter

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

InstallUtil.exe C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe
windows service 
Step 14

Open services by following the below steps,
  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.
windows service
windows service
windows service
Service Output  

windows service 

Log folder will be created in your bin folder.

If you want to uninstall 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\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe
In this article, we learned how to create Windows Service and install/Uninstall it using InstallUtil.exe from a command prompt.

I hope that I have explained each step clearly that can be easily understandable for all developers. You can leave feedback/comment/questions to this article. Please let me know if you like and understand this article and how I could improve it.
I also uploaded this project on GitHub, here is the url