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

可能重复:
如何在C#中以编程方式安装Windows服务?

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

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

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

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

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

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

 var installer = new ProjectInstaller(); installer.Uninstall(null); 

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