我正在尝试编写一个应用程序和服务,监视一组特定的服务,并确保它们在运行,根据某些标准,在需要时重启它们。
但我不断遇到访问被拒绝的错误。
如果我只是在系统上循环遍历进程,像这样找到我想要的那个:
foreach (ServiceController sc in ServiceController.GetServices())
{
if(sc.ServiceName == "MyServiceName")
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
sc.Start();
}
}
我得到:
InnerException: System.InvalidOperationException
Message="Cannot open My Service service on computer '.'."
Source="System.ServiceProcess"
StackTrace:
at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
at System.ServiceProcess.ServiceController.Stop()
at lib.ListServices() in D:\lib.cs:line 552
at lib.Init() in D:\lib.cs:line 56
InnerException: System.ComponentModel.Win32Exception
Message="Access is denied"
ErrorCode=-2147467259
NativeErrorCode=5
InnerException:
我尝试模拟用户,尝试使用另一个作为系统服务运行的服务执行相同的代码。但是这两种方式都没有成功地影响到该服务。如果它已经启动,我就无法停止它。如果它已经停止,我就无法启动它。我知道这一切都与权限有关,只是找不到实际让我控制该服务的机制。
如有帮助,将不胜感激。