Windows服务无法通过ManagedInstallerClass启动但通过InstallUtil成功

时间:2014-09-15 09:55:34

标签: c# windows-services installutil managedinstallerclass

我在Visual Studio 2012(c#)中创建了一个需要在安装后启动的Windows服务。我已经阅读了很多文章和StackOverflow问题,但没有一个工作。 在主要功能中,我有:

static void Main(string []args)
{
     ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
} 

我已经注册了服务的AfterInstall事件。

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
    using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
    {
        sc.Start();
    }
}

我以管理员身份登录。当我运行.exe文件(作为管理员)时,它会尝试安装该服务(使其保持启动状态2分钟)但无法启动它。当我在调试模式下运行时,我在sc.Start()上得到一个异常。日志文件说:

 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.

我尝试将LocalService帐户更改为LocalSystem但没有成功。 然后我尝试更改主要功能

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
        { 
             new Service1() 
        };
ServiceBase.Run(ServicesToRun);

当我installutil convertor.exe,它成功安装并启动服务(但我需要通过该程序启动它)。

为什么在通过installutil进行安装时启动服务?为什么在手动调用installhelper时它会抛出异常?

1 个答案:

答案 0 :(得分:1)

尝试删除服务中OnStart函数中的所有内容,看看它是否成功启动,如果它启动,则调试onStart函数(可以使用Debugger.Attach())

祝你好运