C# – Cannot start service from the command line or debugger

cservicewindows

I've created a windows service and installed it on a server. It appears to work fine ie doing what its meant to do. But when I log on to the server through remote desktop I get this message:

Cannot start service from the command line or 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.

I click on and then go to the services explorer to check the service, its started ok. No errors reported.

I've installed this so it uses Local System as "Log On As".

Thanks.

Best Answer

Change the Main method in Program class as follows:

    /// <summary>
    ///   The main entry point for the application.
    /// </summary>
    private static void Main()
    {
        var myService = new MyService();
        if (Environment.UserInteractive)
        {
            Console.WriteLine("Starting service...");
            myService.Start();
            Console.WriteLine("Service is running.");
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey(true);
            Console.WriteLine("Stopping service...");
            myService.Stop();
            Console.WriteLine("Service stopped.");
        }
        else
        {
            var servicesToRun = new ServiceBase[] { myService };
            ServiceBase.Run(servicesToRun);
        }
    }

You have to add a Start method to your service class:

    public void Start()
    {
        OnStart(new string[0]);
    }

Change the output type of the project to 'Console Application' instead of 'Windows Application' in the 'Application' tab of the project properties. Now you can just press F5 to start debugging but you can still run the executable as a Windows Service.