public
Created

Debugging Windows Services

  • Download Gist
CustomService.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
public partial class CustomService : ServiceBase
{
protected override void OnStop()
{
//normal shutdown code here
}
 
protected override void OnStart(string[] args)
{
//normal startup code here
}
 
public void RunConsole(string[] args)
{
OnStart(args);
 
if ((args.Length > 0) && (Array.IndexOf(args, "/console") != -1))
{
Console.WriteLine("Please press enter to continue...");
Console.ReadLine();
}
 
OnStop();
}
 
}
ServiceStartRedirect.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
public class ServiceStartRedirect
{
#region Methods
 
private static void Main(string[] args)
{
if ((args.Length > 0) && (Array.IndexOf(args, "/console") != -1))
{
var service = new CustomService();
service.RunConsole(args);
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new CustomService()
};
ServiceBase.Run(ServicesToRun);
}
}
 
#endregion
}

In the properties of the project, under Debug -> Start Options -> Command Line Arguments: add

/console

Also make sure in Properties -> Application -> Output type: is set to

Console Application   

and

Startup object: is set to

ServiceStartRedirect

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.