以编程方式安装Windows服务

Jos*_*osh 45 c# windows-services

如何在不使用installutil.exe的情况下以编程方式安装Windows服务?

Mar*_*man 66

您可以通过添加此代码(在程序文件Program.cs中)来安装服务,以便在使用指定参数从命令行运行时自行安装:

/// <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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是一种明确而合适的方法,而不是使用"低级"advapi32.dll,但框架文档说"此API支持.NET Framework基础结构,不能直接在您的代码中使用.".但我仍然更喜欢"ManagedInstallerClass"以及新.net版本中未来不兼容的风险.(http://msdn.microsoft.com/pt-br/library/system.configuration.install.managedinstallerclass) (6认同)

Dan*_*olt 11

我使用以下CodeProject文章中的方法,它工作得很好.

Windows服务可以自行安装

  • 很棒的链接; 然而,它引用了Mahmoud Nasr写的一个链接,这个链接已被破坏.我用过这个,对我有用.https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 (3认同)

Mat*_*vis 5

我通过命令行安装和卸载我的 Windows 服务,例如,MyWindowsService.exe -installMyWindowsService.exe -uninstall,以避免使用installutil.exe我自己。我在此处编写了一组有关如何执行此操作的说明。

  • OP 询问如何以编程方式执行此操作,而不是通过命令行。 (3认同)
  • 我的解决方案是通过命令行访问的程序化解决方案,与接受的答案相同。 (3认同)