2013-06-03 80 views
0

我一直在嘗試通過C#安裝Windows服務幾個小時。無法以編程方式安裝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; 
      } 
     } 
+0

而在程序運行升高嗎?它究竟如何失敗? –

回答

0
public static class SelfInstaller 
{ 
    private static readonly string _exePath = Assembly.GetExecutingAssembly().Location; 

    public static bool InstallMyService() 
    { 
     try 
     { 
      ManagedInstallerClass.InstallHelper(new string[] { _exePath }); 
     } 
     catch 
     { 
      return false; 
     } 
     return true; 
    } 

    public static bool UninstallMyService() 
    { 
     try 
     { 
      ManagedInstallerClass.InstallHelper(new string[] { "/u", _exePath }); 
     } 
     catch 
     { 
      return false; 
     } 
     return true; 
    } 
    public static bool IsInstalled(string serviceName) 
    { 
     var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName); 
     if (serviceExists == null) return false; 
     return true; 
    } 
} 
+0

謝謝,我只是重新啓動我的電腦。順便說一句,你的IsInstalled功能是錯誤的,布爾永遠不能爲空。 – idish

+0

你可以檢查你的服務名稱; http://stackoverflow.com/questions/1841790/how-can-a-windows-service-determine-its-servicename – ramazanulucay