Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

EasyService4Net - Create a Windows Service in 100 Seconds or Less

0.00/5 (No votes)
9 Apr 2016 1  
How to create a program that can run as console or as Windows service easily, and install it without using installutil

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:

  1. System.Configuration.Install
  2. 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

  1. GitHub of EasyService4Net - https://github.com/TheCodeCleaner/EasyService4Net
  2. 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.
  3. 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
  4. I hope you like this tip and will use it for your Windows services from now.
  5. Feel free to write any suggestions or issues you have found.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here