0

I have installed the windows service using installutil service1.exe

When I click Debug, I get the error message Windows Service Start Failure: Cannot start service from the command line or a debugger.... Hence I tried Attach to Process -> Service1 from the Debug menu. However, when I click on Attach to Process, it automatically enters Debug mode and does not respond to any of my break points.

What step am I missing here?

user544079
  • 13,851
  • 35
  • 102
  • 160

1 Answers1

1

The following changes allows you to debug windows services just like any other Console application.

Add this class to your project:

public static class WindowsServiceHelper
{
    [DllImport("kernel32")]
    static extern bool AllocConsole();

    public static bool RunAsConsoleIfRequested<T>() where T : ServiceBase, new()
    {
        if (!Environment.CommandLine.Contains("-console"))
            return false;

        var args = Environment.GetCommandLineArgs().Where(name => name != "-console").ToArray();

        AllocConsole();

        var service = new T();
        var onstart = service.GetType().GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
        onstart.Invoke(service, new object[] {args});

        Console.WriteLine("Your service named '" + service.GetType().FullName + "' is up and running.\r\nPress 'ENTER' to stop it.");
        Console.ReadLine();

        var onstop = service.GetType().GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
        onstop.Invoke(service, null);
        return true;
    }
}

Then add -console to the debug options for the windows service project.

Finally add this to Main in Program.cs:

 // just include this check, "Service1" is the name of your service class.
    if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
        return;

From my blog post An easier way to debug windows services

jgauffin
  • 95,399
  • 41
  • 227
  • 352
  • I added the method. And updated my Debug configuration with "-console". However, when I try to Debug it by pressing F5, I still get the same error – user544079 Jun 26 '13 at 15:29
  • You added it to the wrong textbox. Check the blog post for a screen shot. – jgauffin Jun 26 '13 at 15:31