使用 C# 以编程方式删除服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12201365/
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
Programmatically remove a service using C#
提问by Bender the Greatest
Possible Duplicate:
How to install a windows service programmatically in C#?
Is there a way to programmatically remove a service using C# without having to execute "InstallUtil.exe /u MyService.exe"?
有没有办法使用 C# 以编程方式删除服务而不必执行“InstallUtil.exe /u MyService.exe”?
采纳答案by Mike Christensen
You can use the ServiceInstaller.Uninstall methodin System.ServiceProcess.dll. For example:
您可以使用System.ServiceProcess.dll 中的ServiceInstaller.Uninstall 方法。例如:
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
InstallContext Context = new InstallContext("<<log file path>>", null);
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = "MyService";
ServiceInstallerObj.Uninstall(null);
This method will attempt to stop the service first before uninstalling.
此方法将尝试在卸载之前先停止服务。
回答by L.B
System.Configuration.Install.ManagedInstallerClass
.InstallHelper(new string[] { "/u", executablePath });
回答by KeithS
Services are listed in the Windows Registry under HKLM\SYSTEM\CurrentControlSet\services. If you remove the key corresponding to the service's given name (not the display name; the one under which it was registered), you will have effectively "unregistered" the service. You can do this programmatically with the Microsoft.Win32.Registryobject. You will need CAS permissions on the executing computer to modify registry entries.
服务在 Windows 注册表中的 HKLM\SYSTEM\CurrentControlSet\services 下列出。如果您删除与服务的给定名称(不是显示名称;注册时使用的名称)相对应的密钥,您将有效地“取消注册”该服务。您可以使用Microsoft.Win32.Registry对象以编程方式执行此操作。您将需要执行计算机上的 CAS 权限才能修改注册表项。
回答by Peter Ritchie
If what you are trying to do is to uninstall a service, you've written, from within itself and you've added an installer to the project, you can simply instantiate your Installer class and call Uninstall. For example, if you dragged an installer onto the designer service and named that component "ProjectInstaller", you can get your service to uninstall itself with the following code:
如果您尝试做的是卸载服务,您已经从其内部编写并为项目添加了一个安装程序,您可以简单地实例化您的安装程序类并调用 Uninstall。例如,如果您将一个安装程序拖到设计器服务上并将该组件命名为“ProjectInstaller”,您可以使用以下代码让您的服务自行卸载:
var installer = new ProjectInstaller();
installer.Uninstall(null);

