In this blog post, we will go over on how to create windows services in C#. Windows services are started when OS boots and runs the service in the background. It can start automatically or can be made to start, stop or run based on manual trigger.
Here is how you can create your own windows service:
- Open Visual Studio, go to File > New and select Project. Go to Visual C# -> ”Windows Desktop” -> ”Windows Service,” give your project an appropriate name and then click OK.
- Once you click OK, there will be a black screen with Service1.cs[design] file opened.
- Now, right click on a blank area, and select Add Installer. We need to add installers to windows service before you run the service, which registers with service control managers.
- After adding installer, it adds ProjectInstaller.cs to the project. Once you view the code of Project Installer, you would see InitialiseComponent method.
- Once you go to the definition of it, here you can mention the name of service, description of service, etc.
- Now, you can go back to Service1.cs file, You will see methods like OnStart, OnStop.
- You can now implement a timer or execute a task on the OnStart method and stop it on OnStop.
- Once your code is ready, build the project and go to the folder of bin/debug or bin/release.
- Open command prompt in admin mode, and enter this command
- InstallUtil.exe + Your Path to exe in bin/debug or bin/release
Now your Windows service would have been installed. To verify this, Open Run window (Window + R), type in services.msc, and press enter. You can see a list of services and your service would also be part of it.
If you want to uninstall the service then the command for it is:
InstallUtil.exe -u + Your path to .exe
This is how you can create windows services in C#, Install and uninstall a service.
Thanks for dropping by !!! Please leave a comment to this article or you can drop me an email at email@example.com.