Search code examples
c#.netwindows-servicessetup-projectvisual-studio-setup-proje

How to install a windows service programmatically in C#?


I have 3 projects in my VS solution. One of them is a Web app, the second one is a Windows Service and the last one a Setup project for my Web app.

What I want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that I have the location of the assembly by then.


Solution

  • Ok, here is what REALLY worked for me, it has been tested on multiple machines with different OS ( Vista, XP, Win2k, Win2003 server )

    The code has been taken from here so full credit goes to whoever wrote this piece of code.

    Once you add the dll or source file into your project make sure to add the ServiceTools namespace and then you have access to some very handy functionality such as...

    //Installs and starts the service
    ServiceInstaller.InstallAndStart("MyServiceName", "MyServiceDisplayName", "C:\\PathToServiceFile.exe");
    
    //Removes the service
    ServiceInstaller.Uninstall("MyServiceName");
    
    //Checks the status of the service
    ServiceInstaller.GetServiceStatus("MyServiceName");
    
    //Starts the service
    ServiceInstaller.StartService("MyServiceName");
    
    //Stops the service
    ServiceInstaller.StopService("MyServiceName");
    
    //Check if service is installed
    ServiceInstaller.ServiceIsInstalled("MyServiceName");
    

    I hope this helps.