C# 在 Windows 7 中用代码停止/启动服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1545355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:41:42  来源:igfitidea点击:

Stop/Start service in code in Windows 7

c#windows-7controlsservice

提问by Mark

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.

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

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.

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

Any assistance would be greatly appreciated.

任何帮助将不胜感激。

回答by Bryan

Could it be the .net security policy that is preventing your app from controlling the service?

是否是 .net 安全策略阻止您的应用程序控制服务?

According to MSDN, your assembly needs full trust for this to work.

根据MSDN,您的程序集需要完全信任才能正常工作。

回答by DxCK

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".

我认为这是 UAC 故障...尝试右键单击并“以管理员身份运行”运行 exe。如果这有帮助,您可能希望使用 level="requireAdministrator" 将清单文件添加到您的可执行项目。

回答by Marcusdev

You have to set the application to run as administrator. If you look under the files properties menu. On the compatibility tab, there is a Privilige Level option, to let the program run as administrator. It worked with my own system trays in windows 7.

您必须将应用程序设置为以管理员身份运行。如果您查看文件属性菜单。在兼容性选项卡上,有一个权限级别选项,可以让程序以管理员身份运行。它在 Windows 7 中与我自己的系统托盘一起使用。

回答by Josef

Diagnoses:

诊断:



UAC is indeed the problem. Your application requires elevated user rights. That is why the "run as administrator" works outside of the IDE.

UAC确实是问题所在。您的应用程序需要提升的用户权限。这就是“以管理员身份运行”在 IDE 之外工作的原因。

Some sites suggest disabling UAC. As this is not a possibility in my environment, I decided to request elevated user right via code. Wikipediaprovided the help I needed. The "Requesting elevation" section provides the solution.

一些站点建议禁用 UAC。由于这在我的环境中是不可能的,我决定通过代码请求提升用户权限。维基百科提供了我需要的帮助。“请求提升”部分提供了解决方案。

The solution in short:

解决办法简而言之:



Edit your application manifest file to reflect your requirement.

编辑您的应用程序清单文件以反映您的要求。



1.1. Right click your project
1.2. Click "Properties"
1.3. Select "Application" tab - default page
1.4. Click "View UAC Settings" - This button opens the application manifest file (app.manifest)
1.5. Look for the "UAC Manifest Options" section
1.6. Remove or comment the current entry - {requestedExecutionLevel level="asInvoker" uiAccess="false"}
1.7. Change to {requestedExecutionLevel level="requireAdministrator" uiAccess="false"}. MS provides your 3 options as part of the section comment.

1.1. 右键单击您的项目
1.2。单击“属性”
1.3。选择“应用程序”选项卡 - 默认页面
1.4。单击“查看 UAC 设置” - 此按钮将打开应用程序清单文件 (app.manifest)
1.5。查找“UAC 清单选项”部分
1.6。删除或评论当前条目 - {requestedExecutionLevel level="asInvoker" uiAccess="false"}
1.7。更改为 {requestedExecutionLevel level="requireAdministrator" uiAccess="false"}。MS 提供了 3 个选项作为部分注释的一部分。