Creating Windows Services in C#
To create a Windows service, start Visual Studio, select the Visual C# projects section and select Windows Service as the project type.
Join the DZone community and get the full member experience.
Join For FreeUnlike standard Windows applications, services run in the background and don’t have a GUI, unless managed by another application that can be considered the controller. A service can perform almost anything – it can be a server, a web service host or a web hardware management layer. It has access to pretty much the same system features a regular application has, however it has to be managed in the code-behind only.
To create a Windows service, start Visual Studio, select the Visual C# projects section and select Windows Service as the project type:
Once created, you will see that there is no designer. To jump into the code, press F7 and you should see a code structure similar to this:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Linq;using System.ServiceProcess;using System.Text;namespace testService{ public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { } protected override void OnStop() { } }}
The OnStart event happens when the service starts and the OnStop event occurs when the service stops. For this specific example, I am going to create an application that keeps a log of running processes. Therefore, in the OnStart event I am going to use the following sample code:
string openString = DateTime.Now.ToString() + " | Service Started";string path = @"D:\Temporary\log.txt";List<string> processes = new List<string>();foreach (Process process in Process.GetProcesses()){ processes.Add(process.ProcessName);}if (File.Exists(path)){ using (StreamWriter writer = File.AppendText(path)) { writer.WriteLine(openString); foreach (string item in processes) writer.WriteLine(item); writer.Close(); }}else{ File.WriteAllText(path, openString); using (StreamWriter writer = File.AppendText(path)) { foreach (string item in processes) writer.WriteLine(item); writer.Close(); }}
This basically puts a line in the log file that indicates that the service was started. If the file exists, the line is appended. If not – the file is created in the specified folder. Also, the list of current processes is written to the text file.
When the service stops, it is a good idea to insert a log entry as well. So here goes a snippet for the OnStop event handler:
string stopString = DateTime.Now.ToString() + " | Service Stopped";using (StreamWriter writer = File.AppendText(@"D:\Temporary\log.txt")){ writer.WriteLine(stopString); writer.Close();}
Besides the OnStop and OnStart event handlers, the developer can also work with OnPause and OnContinue.
Let’s customize the service a bit. Return to the initial designer-less page. There, in the bottom right corner you will see the list of available properties:
Instead of the default name (Service1) I named it TestService, so I can easily identify it in the service list later on.
The actual service cannot be installed on the local machine without an installer. To add an installer, right click on the gray background in the designer-less view and select the Add Installer option.
Now, you should see the installer listed:
Select the service process installer (in this case – serviceProcessInstaller1) and change the Account property to LocalService (otherwise authentication will be used):
NOTE: If you are testing on Windows Vista or Windows 7, you might want to set this option to LocalSystem to avoid an Access Denied error.
To test the above code, I need to install the service, since I cannot test it directly from the IDE. Press Ctrl+Shift+B to build the solution. Once the build succeeded, head over to the folder that contains the executable file that was just compiled.
For my specific case, the folder is the following:
C:\Users\Dennis\Documents\Visual Studio 2010\Projects\testService\testService\bin\Debug
There, I can see an executable called testService.exe. That’s exactly the one I was looking for. Now, launch the Visual Studio Command Prompt (in the Start Menu -> Programs -> Microsoft Visual Studio -> Visual Studio Tools). From here, I am going to use INSTALLUTIL to install a service on the local Windows machine. To do this, type the following:
installutil <path to executable>
Once you press ENTER, you should see something like this:
Once you see the message that says that the service was successfully installed, press Win + R on the keyboard to open the Run dialog and type services.msc – this will open the list of services installed on the current machine.
There, you can see the newly installed service:
The startup is set to Manual, so you can right click on it and start the service. Once started, go to the folder that was specified for the log file and see if there is the log entry.
In case you don’t need the service anymore or you want to test another build, use this command to uninstall the service:
Opinions expressed by DZone contributors are their own.
Trending
-
How To Manage Vulnerabilities in Modern Cloud-Native Applications
-
What Is Istio Service Mesh?
-
How Web3 Is Driving Social and Financial Empowerment
-
Building A Log Analytics Solution 10 Times More Cost-Effective Than Elasticsearch
Comments