停止/在Windows代码启动服务7 [英] Stop/Start service in code in Windows 7

查看:291
本文介绍了停止/在Windows代码启动服务7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个应用程序,服务,监控一组给定的服务和)可确保他们正在运行和b)基于一定的标准,根据需要重新启动它们。

I am trying to write a app and service which monitor a given set of services and a) makes sure they are running and b) based on certain criteria, restart them as needed.

我一直运行到拒绝访问错误

I keep running into an access denied error.

如果我只是通过系统上的进程迭代,找到一个我想,像这样:

If I simply iterate through the processes on the system, find the one I want like so:

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



我得到:

I get:

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:

我试图模拟用户,我试图从正在运行作为系统服务的另一个服务做相同的代码。两者都不实际上已经能够影响到服务。如果它的开始,我不能阻止它。如果它停了下来,我无法启动它。我知道这是所有相关的权限,我只是没有找到一种机制,确实让我控制服务。

I have tried to impersonate a user, I have tried to do the same code from another service which is running as a system service. Neither of which have actually been able to affect the service. If its started, I cannot stop it. If its stopped, I cannot start it. I know this is all related to permissions I'm just not finding a mechanism that actually lets me control the service.

任何援助将不胜感激。

推荐答案

我觉得这是UAC的错...
尝试运行右点击以管理员身份运行exe文件。
如果有帮助,你可能要一个清单文件添加到您的使用水平=requireAdministrator可执行项目。

I think this is UAC fault... Try to run the exe with right click and "Run as Administrator". If that helps, you might want to add a Manifest file to your executable project with level="requireAdministrator".

这篇关于停止/在Windows代码启动服务7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆