Creating and Installing Simple Windows Service in C#

Introduction

Windows Service is a background task that runs continuously without user interaction. It is an executable application that can be started, paused and stopped without interaction of the user.

Why do we need Windows Service?

Windows Service is intended to perform long running background tasks for example if you want to notify something to the user with specific intervals of time. If you want to generate a report without disturbing the user Windows Service is the best option to do this.

Creating a Windows Service

First of all, create a new Windows Service, from Classic Desktop project and assign a name to your Service. In Visual Studio 2015 you can create a new Service project from File > New > Project and select Windows Service under Classic Desktop.

New Simple Windows Service
New Simple Windows Service

A new Service project will be created. Open Service1.cs code file either from the Solution Explorer by expanding the Service1.cs file or by right-clicking anywhere on the editor of the Service1.cs[design] view and selecting the Code View or you can also do this by the link in the center of Visual Studio to open the code view.

In the Code View of Service.cs, there will be a constructor that initializes the components and two other methods i.e. OnStart(String[] Args) which is called when the service starts and OnStop() which is called when the service stops.

Writing to a Log Text File

Now create a new class and rename it to WritingLog. You can add a new class file by right-clicking on the Project and from Add > class from the menu. This class will contain two static methods which will write to the text file.

Add new class to write log
Add new class to write log

Writing Events to the Log File

Create a static method writeLog(Exception e). Instantiate and initialize SystemWriter class and pass the directory path of the text file (It will automatically create the file if it does not exist).

Write the date and time to the file along with the Exception and flush the StreamWriter to release the file.

Create another static method writeToLog(String s). Again, initialize SystemWriter object and pass the directory path of the text file. Write down action events log to the log file when service is running. Flush and close the StreamWriter to release the file.

Coming toward the main Windows Service tasks. In Service1.cs file create a Timer object with the class level scope. Initialize the timer object and add the time interval to the timer.  Also, add a delegate that will execute consecutively after the time interval.

implement delegate method to be executed at regular intervals.

In the OnStop() method stop the timer and write to log about the service status.

Complete Code for Service1.cs

Adding Installer and Uninstaller

Open Program.cs file and installer and uninstaller command from System.Configuration.Install.

Now execute the project.

Adding Installer to the Service

Open Service1.cs File and right-click on the visual composer > Add Installer. 

Add Installer to Service in C#
Add Installer to Service in C#

This will add ServiceInstaller and ServiceProcessInstaller to your service.

Installers for Service
Installers for Service

Change the Start type of the ServiceInstaller to Automatic from the Properties, if you want the service to start automatically at Windows start.  Also, change the Service Name to Simple Windows Service as it can be easily found in the Windows Services.

Windows Service Installer Start type to Automatic
Windows Service Installer Start type to Automatic

Now change the Account to LocalSystem from user in the Properties of ServiceProcessInstaller to avoid System.ComponentModel.Win32Exception.

Change ServiceProcessInstaller Account to LocalSystem from User
Change ServiceProcessInstaller Account to LocalSystem from User

 

Installing Service from Developer Command Prompt

To install the service, open Developer Command Prompt of Visual Studio with administrator privileges.

Run Developer Command Prompt as Administrator
Run Developer Command Prompt as Administrator

Install and Uninstall the Service through System.Configuration.Install

Modified Program.cs contains the installer information, so to get rid of InstallUtil.exe you can move to the executable files directory i.e.
Project Root Directory > bin > Debug from Developer Command Prompt and installing the Windows Service by:

ServiceName.exe --install to install the service

Install the Service from System.Configuration.Install
Install the Service from System.Configuration.Install

ServiceName.exe --uninstall to uninstall the service

Uninstall the Service through System.Configuration.Install
Uninstall the Service through System.Configuration.Install

Install and Uninstall the Service through InstallUtil.exe

In the Developers Command Prompt, move to the service executables directory and run InstallUtil.exe with the service name in quotation marks.

Executables directory path:  Project Root Directory > bin > Debug

Command to Install the Service through InstallUtil.exe: InstallUtil.exe "SimpleService.exe"

Installing Service with InstallUtil.exe
Installing Service with InstallUtil.exe

Command to uninstall the Service through InstallUtil.exeInstallUtil.exe \u "SimpleService.exe"

Uninstalling Service with InstallUtil
Uninstalling Service with InstallUtil

Starting the Service

Open services.msc, find the service you previously installed and start it either from the left panel or by right-clicking on the service and click start from the options menu.

Start the Windows Service from services
Start the Windows Service from services

Now the service is started and it will start writing the log. You can find the log files in Project Root Directory > bin > Debug

Windows Service Writing Log
Windows Service Writing Log

When you will stop the service from services.msc, Service will execute OnStop() and perform some task defined in OnStop() method.

Download Simple Windows Service Visual Studio Project (Source Code)

Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed.