Introduction
When you develop a Windows Service and want to run or debug it, you get a message box with this 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 for testing you have to first install it on your computer, but it is a long process and also boring because every time you make changes, you have to reinstall your service and test it again.
Solution
For debugging or testing your service without installing it, make changes in Program.cs like this.
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
}
Change it to:
static class Program
{
static void Main()
{
#if(!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
#else
MyService myServ = new MyService();
myServ.Process();
#endif
}
}
After adding #if
and #else
to your main fuction, now when you press F5 or run your service, it will not show you the previous message and simply run, so attach a break point to your method which will be called by the service when it will start. With the use of this code, you can simply debug your service without installing it.
For this no need to add any extra using directive (like using System.Data
or using System.IO
) to your class file. It will simply as it is.
Enjoy!!!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.