14

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

Community
  • 1
  • 1
codewario
  • 19,553
  • 20
  • 90
  • 159

4 Answers4

24

You can use the ServiceInstaller.Uninstall method in System.ServiceProcess.dll. For example:

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.

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
1
System.Configuration.Install.ManagedInstallerClass
                            .InstallHelper(new string[] { "/u", executablePath });
L.B
  • 114,136
  • 19
  • 178
  • 224
  • For any reason it claims the service is not installed, but it is. It's an external service written in .NET. I got admin rights on my process. – Martin Braun Aug 05 '16 at 09:54
1

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:

var installer = new ProjectInstaller();
installer.Uninstall(null);
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
0

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.Registry object. You will need CAS permissions on the executing computer to modify registry entries.

KeithS
  • 70,210
  • 21
  • 112
  • 164
  • 5
    +1 This may not be recommended, it has the benefit of actually working. :) An alternative is to `CreateProcess sc.exe delete ServiceName`. – Andomar Mar 27 '13 at 17:21