我在 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 时会引发异常?