We all know what a Windows Service is - a long running executable that's designed to work without user interaction. They can be configured to start when the system boots and they can be run without any users logged into the system. This tutorial is going to provide step-by-step instructions on how to build a Windows Service using C# and .NET.
The first thing you're going to want to do is create a new Console Application in Visual Studio. I like to start building services as console applications so they can easily be tested and debugged before converting them to services.

In order to build services, we depend on some .NET objects location in
the System.ServiceProcess and System.Configuration.Install
assemblies. Go ahead and add those references to your project.

When you created the project, Visual Studio should have created a file
called Program.cs, which looks something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class Program
{
static void Main(string[] args)
{
}
}
}
The only thing we need to do in order to make this class into a service
is make Program extend
System.ServiceProcess.ServiceBase.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace MyWindowsService
{
class Program : ServiceBase
{
static void Main(string[] args)
{
}
}
}
By extending ServiceBase, we're given a bunch of service related
functions we can override. At a minimum, every service should override
OnStart and OnStop. These are where, as the names imply, your custom
logic should go when the service is started and stopped.
class Program : ServiceBase
{
static void Main(string[] args)
{
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
There are several other functions beyond start and stop like pause, continue, and shutdown, but they're not needed for a basic service. For all available functions, check out the ServiceBase member list on MSDN.
Now we need to add some information about our service - like a name.
Let's add a constructor to Program and put it there.
class Program : ServiceBase
{
static void Main(string[] args)
{
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
The constructor is where you'd also set lots of other information about your service (if the default settings wouldn't work). These can include things like which events it can handle, what operation it can do (pause, stop, etc.), and what event log it should log information to (application, system, etc.). For us, however, the default settings will work just fine.
We're very close to having a finished service. All that left is to tell
Windows what service to run when your application it executed. Just like
normal applications, execution begins in the Main function. This is
where we'll create an instance of our service and tell it to run.
class Program : ServiceBase
{
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
That's it! The service implementation is complete. We can't install it
yet though, because we haven't implemented an installer. To do that we
need to add another class to our project called
MyWindowsServiceInstaller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class MyWindowsServiceInstaller
{
}
}
When Visual Studio creates a class for you, it doesn't automatically make it public. It's very important that this class be made public. When you install a service, the installer will look through your assembly for public classes with a specific attribute. If it's not public, it won't find it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
public class MyWindowsServiceInstaller
{
}
}
This class needs to extend
System.Configuration.Install.Installer
and be given a RunInstaller attribute. This is the attribute that the
service installer looks for when installing your service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.ComponentModel;
namespace MyWindowsService
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
}
}
Now we need to configure how we want our service installed. We'll do this in the constructor for the class we just created.
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "My Service";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
This is pretty much the bare minimum when it comes to service options.
We have to create a
ServiceProcessInstaller
and a
ServiceInstaller.
These two classes are responsible for installing the service. The
ServiceProcessInstaller installs information common to all services,
and the ServiceInstaller installs information for this specific
service.
The Account property sets which privileges you'd like the service to
run under. The default is User, but then we'd have to specify a
username and a password to determine the account. I chose LocalSystem,
which gives the service a lot (probably too much) access to the local
computer.
Services are identified by name, so you have to ensure
serviceInstaller.ServiceName is exactly the same as what you set in
the constructor of Program. The rest of the options are pretty
obvious. All that's left is to add our two installers to the
Installers collection.
We're done! All that's left to do now is install the service.
Installing The Service
Services are installed using a tool from Microsoft called installutil.exe. This tool is free and is probably already on your computer. I doubt it's in your system path, so you might want to do a quick search for it and add it to your environment variables before continuing.
All you have to do to install your service is open a command prompt, cd to your Release directory, and type:
installutil MyWindowsService.exe

Your service is now installed and ready to go. If you bring up your services manager, you should see one labeled "My Service". Of course, if you start it, nothing will happen since we didn't actually put any code in the OnStart function.

If you want to uninstall the service, you can do so with the same utility but with the "-u" flag.
installutil -u MyWindowsService.exe
There's a lot of power that we haven't even touched in Windows Services, but this tutorial should hopefully give you a starting point on which you can expand and build some much more complex solutions. All of the example code has been attached as a Visual Studio 2008 solution.
Source Files:
I know that's not the point of your post, but i'd like to add one more thing about windows services regarding debug. Create a class library in which you can put all your business logic; this way you can debug the class library with a simple console application, and then after all the tests are done, you add the reference to it on your service project.
That's a good suggestion. Thanks!
Sometimes you just need to get in and debug the service itself to tell what its doing. I include the following code snippet at the beginning of the OnStart method
And here is the static method in my ReflectionUtil class
Basically, if the assembly of the service was compiled in debug mode and in the app directory of the service I find a file called Debug.txt, launch the debugger. If the service is compiled in release mode, it will never go into the debugger. And now I can control if the debugger starts by just touching/removing a text file. I've found this to be extremely useful in hunting down problems.
i think it has to give the detail information about "SimpleServie"
I have just do same your way.but i can't found any file in my app dictory .
I am able to install the service and it is visible in Services window. When I click Start button, it shows a few progress bars and then stops with an error message: Error 1083: The executable program that this service is configured to run in does not implement this service.
I have installed in on my Windows XP Pro. My account has Administrators rights.
How can I fix the error please?
How to show pop up message when service starts running.
Is there any code, please send it to me (email: emsraju@gmail.com)
Thanks -Sunil
By default, services aren't allowed to create user interface elements. You can enable this by going to Services in Computer Management and viewing the Properties for your service. Go to the Log On tab and check "Allow service to interact with desktop". Once you do that, you should be able to create a normal MessageBox. Here's a tutorial that covers MessageBoxes.
I want To convert my Console app into Service. So basically I can copy above code and place my code after base.OnStart(args); Right ?
That would probably work.
Hi, I got the same msg that Piyush Varma :
1083: The executable program that this service is configured to run in does not implement this service.
The service suppose to connect to an Imap server and do 2 or 3 operation. I use the Mailbee .Net Object Lib.
Can someone help me with that issue?
Thanks
Jean-Christophe Fortin web: jeanchristophe.fortin@gmail.com
Very useful tutorial and it works perfectly! Thank you very much!
Nice one :)
Too good...
One note. I found I also had to add using System.ServiceProcess; to the installer class.
Still an A+ tutorial.
cool
great article! I got into some trouble when I try to start the service once it has been listed...I get "Could not start the Myservice service on Local Computer --Error 5: Access is denied"
Great article. I just added my exe code to OnStart event and it worked.
Something missing in Release folder? C# Express 2010.
logfile = C:\Users\Wildfire\Documents\Visual Studio 2010\Projects\MyNewServic e\MyNewService\bin\Release\MyNewService.InstallLog assemblypath = C:\Users\Wildfire\Documents\Visual Studio 2010\Projects\MyNewS ervice\MyNewService\bin\Release\MyNewService.exe Restoring event log to previous state for source My Service. An exception occurred during the Rollback phase of the System.Diagnostics.EventL ogInstaller installer. System.Security.SecurityException: The source was not found, but some or all eve nt logs could not be searched. Inaccessible logs: Security. An exception occurred during the Rollback phase of the installation. This except ion will be ignored and the rollback will continue. However, the machine might n ot fully revert to its initial state after the rollback is complete.
The Rollback phase completed successfully.
This happened to me and to correct it all I needed to do was launch the command prompt as admin. Also I used an account that was an admin on the machine.
Forgot to say, on W7 64bits, is that way to prompt UAC during this installation?
Good Example...
Hi, Can anyone tell how to add installers or to create ServiceProcessInstaller and a ServiceInstaller. Please help me....
Here you go
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
Man, That's like falling off a log! Thanks for the help. I've been using VC6.0 (Studio 2000) to create services because that is the only way I knew how to do it. It was involved, but not too difficult to do. I never found an instructional way to do it in C# under VS2005 --- until now..
All the services I write just spawn threads to do TCP things for me - no advanced service stuff. Now I have a way to install & control a service for me where I can just worry about the problem rather than having to deal (every time) with all the plumbing required to make my code a service.
Again, thanks for the help. Tom Mc
Nice article, but I'd like to see an article that explains how to consume a windows service. It lacks that kind of info on the web
Here is a nice article to get started with Windows service projects.
really nice article http://www.a2zmenu.com/Tutorials/CSharp/Creating-a-Windows-Service-in-CSharp.aspx
I am using VS2010 and in the MyWindowsServiceInstaller Class I think you are missing a reference to the System.ServiceProcess;
Great Article other wise, thanks!
Nicely written!
Very well written... Thanks
This is a great walk through on how to make a service. Thank you very much for your time and effort into putting this together.
Additional note, Win 7, be sure to run the command prompt as admin even if the account is an admin account when using installutil.
Again great job and thanks for your hard work!
When i start my service I get this error...
"The MyService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs."
I'm not to sure why. I have a timer in my code that runs so I know the service shouldn't be shutting down. My Log On tab for the service is set to Local System Account. I am also logged into my comp as admin and installed the service as admin. Not to sure whats going on.
Additional information: Windows 7 x64 Ultimate
If you need to look at my code to help me I'll post it. I'm just at a loss at this point.
Thanks,
Brent
I have same problem... Have anyone idea for this situation ?
My code in override OnStart and OnStop method is :
protected override void OnStart(string[] args) { base.OnStart(args);
FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine(" mcWindowsService: Service Started \n"); m_streamWriter.Flush(); m_streamWriter.Close(); //TODO: place your start code here }
protected override void OnStop() { base.OnStop();
FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n"); m_streamWriter.Flush(); m_streamWriter.Close();
//TODO: clean up any variables and stop any threads }
Good post
Getting the following error while trying to start the service:
Windows could not start the My Service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion.
Any help?
(Anonymous 06/01/2011 - 12:48): Windows is expecting service to return control to it after the start, and gives a service a specific time to start properly. If your code is doing a slow operation on start, such as DB connection, huge file loading or indexing .. etc, you better off taking out this code from OnStart() function, and instead creating a one-off timer in there with even 100 ms delay. Then Windows will get control right after creating the timer and your service will start. But when the timer fires - you can do there your slow operation and that's where your logic can start.
Good tutorial and works for me :)
I need any documentation for detail information about windows service like W3 School
Hello, greate tutorial, but I have problem with generation (make) services. I have Win7, this tutorial is for what windows?
I has error: In the appellate stage of installation services System.Diagnostics.EventLogInstaller exception occurred. System.Security.SecurityException: The source was not found, but some or all event logs can not be searched.
Please help me. Thanks
I thought i would share how to debug a Win Ser
add this line to your code and the debugging will start
System.Diagnostics.Debugger.Break(); (C#)
Very nice and clear way written *THUMBS UP* thanks alot!
good one it helped me a lot thanks
If all you want to do is run your console application as a service without having to re-code it may I recommend: http://runasservice.com
Nice article. Great to see a stripped down version of a Windows service without all the extra crap created by the IDE.
very clear! thank you very much
Hi If you have problems instaling your windows service under Windows 7 os, try puting it on disk where your operating system is instaled, default c:\ , and copy InstallUtil.exe to your directory where the .exe is for your service. Hope this helps
Good one!!!!
serviceInstaller.DisplayName = "My Service"; serviceInstaller.StartType = ServiceStartMode.Manual; serviceInstaller.ServiceName = "My Service";
i cant acces these three properties in console application class..i can create object for "ServiceInstaller" class but these three properties not displaying in list..
can any one help!!!
Thanks in Advance:):)
http://www.c-sharpcorner.com/UploadFile/mahesh/window_service11262005045007AM/window_service.aspx
it's Clearly. thank you.
Thank you, great for a beginner (Me)!
I have a console app which I'm doing various collections of system information. This process can take a minute or so on slower machines.
If I convert this to a service, is the OnLoad() method the best place to be doing this? I'm just concerned that if it takes time, the service may timeout when attempting to start.
You should probably do the work in a thread. The quickest way to get one is by using the Threadpool.
I'm having an issue, I have a service that listen for TCP Packets and save them into a SQL database, it works pretty good for the first couple of minutes (when in the Services Manager says that it's starting) but after the service manager says that is completely started, the service do not log in the database anymore.
Have an idea about this issue??
Very nice and informative post. It provides me basic knowledge about windows service using c# code. Thanks for sharing with us. I've checked another posts while I'm wondering over the internet, related to this post. That post also explained very well on windows service which I was checked. Here I want to share that posts link, please visit.... http://www.aspdotnet-suresh.com/2011/06/creating-windows-service-in-c-or.html and http://mindstick.com/Articles/fd4971ba-7e48-4f1a-9aa1-621748a98e9f/?Windows%20Service
kewl tute man...works like a charm
i need to work service as a background process. how to do it.
This was my first windows service and it worked w/o a hitch. Thanks for every detail in your tutorial.
Anyone have the windows service .zip file template for C# 2010 Express?
Perfect, Thank you!
Thanks a lot. Very helpful tutorial
HI:) Thanks a Lot it was very helpful
Very Interesting and Very Good Article to learn windows services .