I created a batch file for installing service because I need to install my service on PC don't have Visual Studio.
Content of batch file:
@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
echo Installing service complete
pause
And I need to autostart MyService after install, so I make this code:
private void svInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(svInstaller.ServiceName);
sc.Start();
}
Don't any problem if I installing my service by Visual Studio Command Prompt with InstallUtil. When I install service by batch file, my service didn't autostart.
How to possible to auto start my service after install by batch file?
Update: Thanks Sam Denty's answer, I problem is resolved.
But I have another question: When I install my service by sc, my code in AfterInstall function do not work?
This is possible by using either the net start service
or sc start
command (see previous question on that).
To start a service using sc start
, the syntax is:
sc [<ServerName>] start <ServiceName> [<ServiceArguments>]
<ServerName>
Specifies the name of the remote server on which the service is located. The name must use the Universal Naming Convention (UNC) format (for example, \\myserver). To run SC.exe locally, omit this parameter.
<ServiceName>
Specifies the service name returned by the getkeyname operation.
<ServiceArguments>
Specifies the service arguments to pass to the service to be started.
Example:
sc start MyService
Updated script:
@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
sc start MyService
echo Installing service complete
pause
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With