Monday, 29 March 2010

How to Run a Windows Service as a Console App in Debug Mode

1. Right click on your windows service project, go to the properties and change the Output Type to Console Application.

2. In the Main method of your Program.cs file, write the following:

static class Program
{
///
/// The main entry point for the application.
///
static void Main()
{
Service1 service1 = new Service1();

if (Environment.UserInteractive)
{
service1.RunAsCommandLineApplication();
}
else
{
ServiceBase.Run(service1);
}
}
}

3. Add the following method to your Service1 windows service:

internal void RunAsCommandLineApplication()
{
this.OnStart(null);
Console.WriteLine("The Service is running.");
Console.WriteLine("Press return to quit application.");
Console.ReadLine();
this.OnStop();
}

4. Install your service using the svcutil.exe tool or using a Setup project

Now you can run your windows service as a console application in debug mode.

No comments: