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" };
		service.StartFromDebugger(args);
	}
	else
	{
		// We are running as a service so start normally.
		ServiceBase[] ServicesToRun;
		ServicesToRun = new ServiceBase[] 
		{ 
			new Service1() 
		};
		ServiceBase.Run(ServicesToRun);
	}
}

// IN YOUR SERVICE
public partial class Service1 : ServiceBase
{
	public void StartFromDebugger(string[] args)
	{
		OnStart(args);
	}
	
	// Normal service code
}
Advertisements