使用C#以编程方式删除服务

时间:2012-08-30 16:24:52

标签: c# .net windows-services

  

可能重复:
  How to install a windows service programmatically in C#?

有没有办法以编程方式使用C#删除服务而无需执行“InstallUtil.exe / u MyService.exe”?

4 个答案:

答案 0 :(得分:20)

您可以在System.ServiceProcess.dll中使用ServiceInstaller.Uninstall method。例如:

ServiceInstaller ServiceInstallerObj = new ServiceInstaller(); 
InstallContext Context = new InstallContext("<<log file path>>", null); 
ServiceInstallerObj.Context = Context; 
ServiceInstallerObj.ServiceName = "MyService"; 
ServiceInstallerObj.Uninstall(null); 

此方法将在卸载前尝试先停止服务。

答案 1 :(得分:1)

System.Configuration.Install.ManagedInstallerClass
                            .InstallHelper(new string[] { "/u", executablePath });

答案 2 :(得分:1)

服务在HKLM \ SYSTEM \ CurrentControlSet \ services下的Windows注册表中列出。如果删除与服务的给定名称相对应的密钥(不是显示名称;注册该名称的密钥),您将有效地“取消注册”该服务。您可以使用Microsoft.Win32.Registry对象以编程方式执行此操作。您将需要执行计算机上的CAS权限来修改注册表项。

答案 3 :(得分:1)

如果你要做的是卸载一个服务,你已经从内部编写了,并且你已经为项目添加了一个安装程序,你可以简单地实例化你的Installer类并调用Uninstall。例如,如果您将安装程序拖到设计器服务上并将该组件命名为“ProjectInstaller”,则可以使用以下代码将服务卸载自己:

var installer = new ProjectInstaller();
installer.Uninstall(null);
相关问题