2010-01-15 220 views
37

如何在不使用installutil.exe的情況下以編程方式安裝Windows服務?以編程方式安裝Windows服務

+0

而不使用任何其他第三方安裝程序? – 2010-01-15 14:40:13

+0

是的....我希望我可以使用像installservice()這樣的功能,當我雙擊windowsservice.exe時,它會檢查它的安裝,如果沒有安裝,它會自行安裝。 – Josh 2010-01-15 14:42:55

+1

這是一個很好的功能:) :) – Danail 2010-01-15 14:46:00

回答

54

可以通過添加該代碼安裝服務(在程序文件,Program.cs中)使用指定的參數從命令行運行時自行安裝文章,而且效果很好。

Windows Services Can Install Themselves

+0

該鏈接已關閉。 – 2011-05-05 23:37:03

+6

雖然這是一個清晰且合適的方式,但不是使用「低級」advapi32.dll,框架文檔中提到「此API支持.NET Framework基礎結構,不能直接在您的代碼中使用」。但我仍然更喜歡「ManagedInstallerClass」以及新的.net版本未來不兼容的風險。 (http://msdn.microsoft.com/pt-br/library/system.configuration.install.managedinstallerclass) – Luciano 2012-08-08 18:06:54

3

我通過命令行安裝和卸載我的Windows服務,例如MyWindowsService.exe -installMyWindowsService.exe -uninstall,以免我自己使用installutil.exe。我寫了一套關於如何做到這一點的說明here

/// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     static void Main(string[] args) 
     { 
      if (System.Environment.UserInteractive) 
      { 

       if (args.Length > 0) 
       { 
        switch (args[0]) 
        { 
         case "-install": 
          { 
           ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); 
           break; 
          } 
         case "-uninstall": 
          { 
           ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); 
           break; 
          } 
        } 
       } 
      } 
      else 
      { 
       ServiceBase[] ServicesToRun; 
       ServicesToRun = new ServiceBase[] { new MyService() }; 
       ServiceBase.Run(ServicesToRun); 
      } 
     } 
+0

該OP問如何以編程方式做到這一點,而不是通過命令行。 – Mike 2017-11-03 03:38:36

+0

我的解決方案是一種程序化的解決方案,通過命令行以與接受的答案相同的方式訪問。 – 2017-11-03 15:46:47

9

我用從以下CodeProject上的方法:

+2

偉大的鏈接;但是,它引用了馬哈茂德納斯爾寫的一個斷章。我用這個,它適用於我。 https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 – 2017-01-18 21:41:42

+1

雖然此鏈接可能會回答這個問題,最好在這裏包含答案的重要部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/18705889) – amod 2018-02-02 17:53:47