Question

I am running a Windows service on my production server. It is super-important that we have immediate recovery if the service crashes for any reason, so I wrote a monitor service whose sole purpose in life is to keep checking that the main service is up and running, and if it's not, to send out a distress signal. It's also supposed to start up the service that's down... and that's the part that's not working:

public static void CheckService(string checkServiceName, string myServiceName, bool restartIfStopped = false)
{
    var ctl = ServiceController.GetServices()
         .FirstOrDefault(s => s.ServiceName == checkServiceName);
    var error = "";
    if (ctl == null)
        error = "{0} is not installed!".Fmt(checkServiceName);
    else if (ctl.Status != ServiceControllerStatus.Running)
    {
        error = "{0} is in status {1}".Fmt(checkServiceName, ctl.Status);
        if (restartIfStopped)
            try
            {
                ctl.Start();
                // no error = success
                error += "\r\nService was automatically restarted.";
            }
            catch (Exception ex)
            {
                // send to windows application log
                Log("Failed to restart service:\r\n"+ex, myServiceName, EventLogEntryType.Warning);
            }
    }
    // other code here to send out email notifications
}

The problem is that when I try to restart the service with ctl.Start(), it exceptions out with the following error in the application log:

Failed to restart service:

System.InvalidOperationException: Cannot open MyService service on computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied

Both services are set to run using "Network service". I have granted full security permission to "Network Service" on both the executable folders.

What else could be causing this?

Was it helpful?

Solution

You can set the service to restart in case of failure (as described here).

OTHER TIPS

It looks like its an Administrative Permission.

I would try 2 things

  1. Add Application Manifest to the solution, for more details refer : http://www.codeproject.com/Questions/629067/How-to-add-a-manifest-file-in-my-project

  2. Give Manual rights

Go to c://Program Files/ApplicationFolder/.exe Right click on .exe and go to Properties then go Compability Tab and check true to Run this Program as an administrator Level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top