小编Mar*_*ark的帖子

Windows 7中的代码中的停止/启动服务

我正在尝试编写一个应用程序和服务来监视一组给定的服务,并且a)确保它们正在运行,并且b)根据某些标准,根据需要重新启动它们.

我一直遇到拒绝访问错误.

如果我只是遍历系统上的进程,找到我想要的那样:

foreach (ServiceController sc in ServiceController.GetServices())
   {                
       if(sc.ServiceName == "MyServiceName")
       {
            sc.Stop();
            sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
            sc.Start(); 
       }            
   }   
Run Code Online (Sandbox Code Playgroud)

我明白了:

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: 
Run Code Online (Sandbox Code Playgroud)

我试图冒充用户,我试图从另一个作为系统服务运行的服务中执行相同的代码.这些都没有真正能够影响服务.如果它开始了,我无法阻止它.如果它停止了,我无法启动它.我知道这都与权限有关我只是没有找到实际上让我控制服务的机制.

任何帮助将不胜感激.

c# service controls windows-7

20
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

controls ×1

service ×1

windows-7 ×1