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
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.
-
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
-
1It also wouldn't hurt to wrap the
ServiceController
in a using statement.– ChrisOCommented Oct 21, 2013 at 10:00 -
3
-
1serviceInstaller is supposed to be the
ServiceInstaller
variable in your class. Such class shall implementSystem.Configuration.Install.Installer
. See this msdn guide for more information. Commented Jan 17, 2017 at 12:44 -
4@PhilipRego Presumably
serviceInstaller
is theServiceInstaller
object referred to bysender
in the event handler, which is normally instantiated in theServiceInstaller()
constructor. Therefore you might addServiceInstaller serviceInstaller = (ServiceInstaller)sender;
before theusing
statement. Commented Feb 10, 2017 at 1:20
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();
}
}
}
-
2This 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.– goamnCommented May 1, 2014 at 1:27
-
2The 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.– goamnCommented 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 Commented Feb 28, 2018 at 14:21
How about following commands?
net start "<service name>"
net stop "<service name>"
-
Cool. I wrote this in my installation batch file right after the installation is done. Commented Jan 16, 2020 at 16:01
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
viaRunspaceInvoke
or by creating your ownRunspace
and using itsCreatePipeline
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
You can use the following command line to start the service:
net start *servicename*
Here is a procedure and code using generated ProjectInstaller
in Visual Studio:
- Create Windows Service project in Visual Studio
- Generate installers to the service
- Open
ProjectInstaller
in design editor (it should open automatically when installer is created) and set properties of generatedserviceProcessInstaller1
(e.g. Account: LocalSystem) andserviceInstaller1
(e.g. StartType: Automatic) - Open
ProjectInstaller
in code editor (pressF7
in design editor) and add event handler toServiceInstaller.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();
}
}
}
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".
-
6Why is "sc" a "more correct" way? What is wrong with "net start" (and start-service PSH cmdlet)?– RichardCommented Jun 24, 2009 at 8:14
-
1Because sc can be called from a remote machine, so it always works. Commented Dec 4, 2015 at 1:30
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();
}
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.
-
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. 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
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..).
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.
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.
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();
}
}
}