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

本文关键字:启动 InstallUtil 成功 服务 Windows ManagedInstallerClass | 更新日期: 2023-09-27 18:21:50

我在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);

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

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

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

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

祝好运