2010-01-15 223 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