Create A Windows Service In C#

This article introduces Windows Services in .NET and how to create a Windows Service in C# and .NET using Visual Studio.

What is a Windows Service?

Windows Services are non-UI software applications that run in the background. Windows services usually start when an operating system boots and is scheduled to run in the background to execute some tasks. Windows services can also be started automatically or manually. You can also manually pause, stop and restart Windows services. 

Windows service is a computer program that runs in the background to execute some tasks. Some examples of Windows services are auto-update of Windows, check emails, print documents, SQL Server Agent, file and folder scanning and indexing, etc. If you open your Task Manager and click on the Services tab, you will see hundreds of services running on your machine. You can also see the statuses of these services. Some services are running, some have paused, and some have stopped. You can start, stop, and pause a service from here by right click on the service. 

Windows Service in CSharp

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

  • Go to Control Panel and select "Services" inside "Administrative Tools."
  • Next, open the Run window (Window + R), 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, click File > New, and select a project. Next, select a new project from the Dialog box, select "Window Service," and click the OK button.

windows service

Step 2

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

windows service 

Once you click the 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."

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.

windows service 

After Adding Installer, ProjectInstaller will add to your project, and ProjectInstakker.cs file will be open. Don't forget to save everything (by pressing the ctrl + shift + s key)

windows service 

Solution Explore looks like this:

windows service 

Step 4

Right-click on the blank area and select "View Code"

windows service

Step 5

It has Constructor, which contains the InitializeComponent method:

The InitializeComponent method contains the logic which creates and initializes the user interface objects dragged on the forming surface and provides the Property Grid of Form Designer.

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

windows service 

Step 6

Select the InitializeComponent method and press the F12 key to go definition.

windows service 

Step 7

Now add the below line:

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

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

this.serviceInstaller1.Description = "My First Service demo";  
this.serviceInstaller1.DisplayName = "MyFirstService.Demo";  

windows service

Step 8

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

windows service 

Service1.cs class

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Diagnostics;  
using System.IO;  
using System.Linq;  
using System.ServiceProcess;  
using System.Text;  
using System.Threading.Tasks;  
using System.Timers;  
namespace MyFirstService {  
    public partial class Service1: ServiceBase {  
        Timer timer = new Timer(); // name space(using System.Timers;)  
        public Service1() {  
            InitializeComponent();  
        }  
        protected override void OnStart(string[] args) {  
            WriteToFile("Service is started at " + DateTime.Now);  
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
            timer.Interval = 5000; //number in milisecinds  
            timer.Enabled = true;  
        }  
        protected override void OnStop() {  
            WriteToFile("Service is stopped at " + DateTime.Now);  
        }  
        private void OnElapsedTime(object source, ElapsedEventArgs e) {  
            WriteToFile("Service is recall at " + DateTime.Now);  
        }  
        public void WriteToFile(string Message) {  
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
            if (!Directory.Exists(path)) {  
                Directory.CreateDirectory(path);  
            }  
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";  
            if (!File.Exists(filepath)) {  
                // Create a file to write to.   
                using(StreamWriter sw = File.CreateText(filepath)) {  
                    sw.WriteLine(Message);  
                }  
            } else {  
                using(StreamWriter sw = File.AppendText(filepath)) {  
                    sw.WriteLine(Message);  
                }  
            }  
        }  
    }  
}

Code explanation - the above code will call service every 5 seconds, 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 the full path of your Windows Service exe file.

windows service

windows service

Installing a Windows Service

Open the 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\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

windows service 

Check the status of a Windows Service.

Open services by following the below steps:

  1. Press the 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. 

windows service 

The 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\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

Summary

This article taught us how to create a Windows Service and install/Uninstall it using InstallUtil.exe from the command prompt.

I hope you found this tutorial easy to follow and understand. 

I also uploaded this project on GitHub; here is the URL https://github.com/faisal5170/WindowsService.


Similar Articles