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?