Debugging a Windows Service in C#

Writing a Windows Service in .NET is as easy as selecting the…wait for it…”Windows Service” project type for your new project. However, debugging a service is more difficult. Typically you will start the service, locate the process name, and manually attach a debugger to it, which is 2.5 steps too many for me.

If you try and F5 it from Visual Studio, you will receive the following error message:

Cannot start service from the command line or a debugger. A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

So how do you start a service from Visual Studio? The answer is actually quite simple. Simply change your Main method to check if you are debugging and, if so, jump straight into your service (providing a suitable entry point in your service of course).

static void Main()
	if (System.Diagnostics.Debugger.IsAttached)
		// We are running with a debugger attached, so start
		// the service directly.
		Service1 service = new Service1();
		string[] args = new string[] { "arg1", "arg2" };
		// We are running as a service so start normally.
		ServiceBase[] ServicesToRun;
		ServicesToRun = new ServiceBase[] 
			new Service1() 

public partial class Service1 : ServiceBase
	public void StartFromDebugger(string[] args)
	// Normal service code

One thought on “Debugging a Windows Service in C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s