几个小时以来,我一直在尝试通过 C# 安装 Windows 服务。
当我运行该InstallService()
函数时,IsInstalled()
即使在InstallService()
运行后也返回 false,因此我无法启动 windows 服务。
例如:
InstallService();
IsInstalled(); // false
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun); //Throws an exception because uninstalled!
所以这是安装代码,我只显示相关代码:
private static void InstallService()
{
if (IsInstalled()) return;
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Install(state);
installer.Commit(state);
}
catch
{
try
{
installer.Rollback(state);
}
catch { }
throw;
}
}
}
catch
{
throw;
}
}
private static AssemblyInstaller GetInstaller()
{
AssemblyInstaller installer = new AssemblyInstaller(
typeof(Service1).Assembly, null);
installer.UseNewContext = true;
return installer;
}
private static bool IsInstalled()
{
using (ServiceController controller =
new ServiceController("Service1"))
{
try
{
ServiceControllerStatus status = controller.Status;
}
catch
{
return false;
}
return true;
}
}