2013-06-03 4 views
0

J'ai essayé d'installer un service Windows via C# pendant quelques heures.Impossible d'installer un service Windows par programme

Lorsque j'exécute la fonction InstallService(), IsInstalled() renvoie la valeur false même après l'exécution de InstallService(), et je ne parviens donc pas à démarrer le service Windows.

Par exemple:

InstallService(); 
IsInstalled(); // false 
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() }; 
ServiceBase.Run(ServicesToRun); //Throws an exception because uninstalled! 

Alors, voici le code d'installation, je montre que le code correspondant:

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

Et le programme est en cours d'exécution droit élevé? Comment cela échoue-t-il exactement? –

Répondre

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

Merci, j'ai juste dû redémarrer mon ordinateur .. BTW, votre fonction IsInstalled est faux, bool ne peut jamais être nulle. – idish

+0

Pouvez-vous vérifier le nom de votre service? http://stackoverflow.com/questions/1841790/how-can-a-windows-service-determine-its-servicename – ramazanulucay

Questions connexes