Automatically start a Windows Service on install

How to automatically start a Windows Service on install. In C# you can create windows service that run in the background under services. To install windows service you use install util command. When the service is installed in the system, you can check it under services.

Let’s say you service name is ‘MyService’ that you installed using installutil. To check the service is installed successfully take these steps:

1. Open ‘Run’ from start menu.

2. Type ‘Services.msc’ and hit Enter.

3. You will see the list of all services installed in your system.

4. Find your service ‘MyService’ in the list.

5. You can check the status column if it’s running or not.

6. You can manually run or stop the service using double click and choose desired option.

 

But sometimes you want service to be run automatically when you install it. So that you need not to come here and start it manually. To do this you need to do following steps.

In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service.

 

public ServiceInstaller()
{
    //... Installer code here
    this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}

void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
    {
        sc.Start();
    }
}

Now when you run InstallUtil on your installer it will install and then start up the service.

How to install windows service using ‘installutil.exe’

1. Open Visual studio Command Prompt with ‘Administrator’ rights.

2. Run the below command there

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "c:\myservice.exe

 

3. Check the confirmation message of service installed successfully.

it’s done

How to uninstall windows service using ‘installutil.exe’

1. Open Visual studio Command Prompt with ‘Administrator’ rights.

2. Run the below command there

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" /u "c:\myservice.exe

 

3. Check the confirmation message of service uninstalled successfully.

it’s done