Introduction
If you ever wanted to created a new Windows service that would be able to run as console as well you know it may be really annoying, and can take much time.
In this tip, I will explain how it can be done very easily.
Using the Code
Open a new Visual Studio console application and add the EasyService4Net
nuget package to it:
In Program.cs file, add usings
:
using System.IO;
using EasyService4Net;
Write the following code in the Main
function:
static void Main(string[] args)
{
var easyService = new EasyService();
easyService.OnServiceStarted +=
() => File.WriteAllText("C:\\exampleFile.txt", "Hello World!");
easyService.Run(args);
}
Here, you can write the code that you want to run when the service starts. In this example, it will write "Hello World
" in a file.
Now you need to add two empty classes to the project (without it, the Windows service won't work!):
using EasyService4Net.ServiceInternals;
public class EasyServiceInstaller : ProjectInstaller { }
public class EasyServiceService : InternalService { }
And add two references to the project:
System.Configuration.Install
System.ServiceProcess
That's it, now you can install the service as Windows service:
Run the cmd as administrator (In order to install Windows service, you must be administrator), go to the folder where the compiled code is found and write (if your EXE is called MyEasyService
):
MyEasyService.exe -install
Your Windows service is running:
You can enter services.msc and see it:
If you open the file "C:\\example.txt", you will see "Hello World
" written in it.
If you want to uninstall the service, all you need to do is this:
MyEasyService.exe -uninstall
Pay attention that you can also run this program as a console (as administrator):
Notes
- GitHub of EasyService4Net - https://github.com/TheCodeCleaner/EasyService4Net
- If you don't want to be dependent on the EasyService4Net nuget, you can simply take its code to your project, and manage it by yourself.
- StackOverflow answer on how to make applications run as administrator by default (very useful)- http://stackoverflow.com/questions/2818179/how-to-force-my-net-app-to-run-as-administrator-on-windows-7
- I hope you like this tip and will use it for your Windows services from now.
- Feel free to write any suggestions or issues you have found.