I have created a windows service in Visual studio 2012 (c#) that needs to be started after install. I have read so many articles and StackOverflow questions but none got it working. In the main function, I have:
static void Main(string []args)
{
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
}
I have registered AfterInstall event of the service.
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
{
sc.Start();
}
}
I'm logged in as an administrator. When I run the .exe file (as administrator), it tries to installs the service (keeps it in starting status for 2 minutes) but fails to start it. When I run in debug mode, I get an exception on sc.Start(). The log file says:
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 Database Convertor on computer '.'.
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: The service did not respond to the start or control request in a timely fashion.
I tried to change LocalService account to LocalSystem with no success. Then I tried changing the main function too
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
and when I installutil convertor.exe, it successfully installs and starts the service (but I need to start it through the program).
Why it starts the service when installing through installutil and why it throws an exception when I manually call installhelper?