126

I have a Windows Service which I install using the InstallUtil.exe. Even though I have set the Startup Method to Automatic, the service does not start when installed, I have to manually open the services and click start. Is there a way to start it either via the command line, or through the code of the Service?

13 Answers 13

233

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.

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

void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceInstaller serviceInstaller = (ServiceInstaller)sender;

    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 automatically.

9
  • 40
    (comment from a proposed edit): Better to use serviceInstaller.ServiceName, if the servicename gets changed it will use the correct name without needing to change it in the code. Commented Feb 1, 2011 at 9:46
  • 1
    It also wouldn't hurt to wrap the ServiceController in a using statement.
    – ChrisO
    Commented Oct 21, 2013 at 10:00
  • 3
    How are you getting serviceInstaller? Commented Dec 1, 2016 at 16:47
  • 1
    serviceInstaller is supposed to be the ServiceInstaller variable in your class. Such class shall implement System.Configuration.Install.Installer. See this msdn guide for more information. Commented Jan 17, 2017 at 12:44
  • 4
    @PhilipRego Presumably serviceInstaller is the ServiceInstaller object referred to by sender in the event handler, which is normally instantiated in the ServiceInstaller() constructor. Therefore you might add ServiceInstaller serviceInstaller = (ServiceInstaller)sender; before the using statement.
    – khargoosh
    Commented Feb 10, 2017 at 1:20
33

After refactoring a little bit, this is an example of a complete windows service installer with automatic start:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
    private readonly ServiceProcessInstaller processInstaller;
    private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;

    public ServiceInstaller()
    {
        InitializeComponent();
        processInstaller = new ServiceProcessInstaller();
        serviceInstaller = new System.ServiceProcess.ServiceInstaller();

        // Service will run under system account
        processInstaller.Account = ServiceAccount.LocalSystem;

        // Service will have Automatic Start Type
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = "Windows Automatic Start Service";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);
        serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;            
    }
    private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        ServiceController sc = new ServiceController("Windows Automatic Start Service");
        sc.Start();
    }
}
}
3
  • 2
    This code gave me the following error/s: An exception occurred during the Install phase. System.InvalidOperationException: An exception occurred in the OnAfterInstall event handler of System.ServiceProcess.ServiceInstaller. The inner exception System.InvalidOperationException was thrown with the following error message: Cannot start service serviceName on computer '.'.. The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: The executable program that this service is configured to run in does not implement the service.
    – goamn
    Commented May 1, 2014 at 1:27
  • 2
    The errors seized once I commented out the line "InitializeComponent()". I believe this line is duplicating all the other lines as the logs seem to show two identical things happening at together before the error: Installing service serviceName... Service serviceName has been successfully installed. Creating EventLog source serviceName in log Application... Installing service serviceName... Creating EventLog source serviceName in log Application... An exception occurred in the OnAfterInstall event handler of System.ServiceProcess.ServiceInstaller.
    – goamn
    Commented May 1, 2014 at 1:28
  • You really saved my day :) Thank you for this useful comment. After I had commented out InitializeComponent() call, my service also started perfectly
    – Konstantin
    Commented Feb 28, 2018 at 14:21
10

How about following commands?

net start "<service name>"
net stop "<service name>"
1
  • Cool. I wrote this in my installation batch file right after the installation is done. Commented Jan 16, 2020 at 16:01
5

Programmatic options for controlling services:

  • Native code can used, "Starting a Service". Maximum control with minimum dependencies but the most work.
  • WMI: Win32_Service has a StartService method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).
  • PowerShell: execute Start-Service via RunspaceInvoke or by creating your own Runspace and using its CreatePipeline method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.
  • A .NET application can use ServiceController
4

You can use the following command line to start the service:

net start *servicename*
4

Here is a procedure and code using generated ProjectInstaller in Visual Studio:

  1. Create Windows Service project in Visual Studio
  2. Generate installers to the service
  3. Open ProjectInstaller in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1 (e.g. Account: LocalSystem) and serviceInstaller1 (e.g. StartType: Automatic)
  4. Open ProjectInstaller in code editor (press F7 in design editor) and add event handler to ServiceInstaller.AfterInstall - see the following code. It will start the service after its installation.

ProjectInstaller class:

using System.ServiceProcess;


[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent(); //generated code including property settings from previous steps
        this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
    }

    void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
    {
        ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
        using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
        {
            sc.Start();
        }
    }
}
2
  • this one helps me as I am using ProjectInstaller. thank you!
    – HadidM
    Commented Jun 7, 2023 at 8:54
  • I try the same but it doesn't work Commented Aug 19, 2023 at 4:35
2

Use ServiceController to start your service from code.

Update: And more correct way to start service from the command line is to use "sc" (Service Controller) command instead of "net".

2
  • 6
    Why is "sc" a "more correct" way? What is wrong with "net start" (and start-service PSH cmdlet)?
    – Richard
    Commented Jun 24, 2009 at 8:14
  • 1
    Because sc can be called from a remote machine, so it always works. Commented Dec 4, 2015 at 1:30
1

Despite following the accepted answer exactly, I was still unable to get the service to start-- I was instead given a failure message during installation stating that the service that was just installed could not be started, as it did not exist, despite using this.serviceInstaller.ServiceName rather than a literal...

I eventually found an alternative solution that makes use of the command line:

private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/C sc start " + this.serviceInstaller.ServiceName;

        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
    }
0

Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.

2
  • I do not wish to do this. I am looking to do this in one go from the command line, or from within the Windows Service classes.
    – mickyjtwin
    Commented Jun 24, 2009 at 6:41
  • Sorry, my bad, I missed the point where you explicitly excluded the possibility of starting it over the control panel. Commented Jun 24, 2009 at 6:54
0

You can use the GetServices method of ServiceController class to get an array of all the services. Then, find your service by checking the ServiceName property of each service. When you've found your service, call the Start method to start it.

You should also check the Status property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

0

You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.

0

Just a note: You might have set up your service differently using the forms interface to add a service installer and project installer. In that case replace where it says serviceInstaller.ServiceName with "name from designer".ServiceName.

You also don't need the private members in this case.

Thanks for the help.

0

This is OK for me. In Service project add to Installer.cs

[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }
 
    protected override void OnAfterInstall(IDictionary savedState)
    {
        base.OnAfterInstall(savedState);
 
        //The following code starts the services after it is installed.
        using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            serviceController.Start();
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.