以编程方式安装Windows服务

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

谢谢

您可以通过添加此代码(在程序文件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); } } 

我使用下面的CodeProject文章中的方法,它工作的很好。

Windows服务可以自行安装

我通过命令行(例如, MyWindowsService.exe -installMyWindowsService.exe -uninstall )来安装和卸载Windows服务,以免我自己使用installutil.exe 。 我已经写了一套如何在这里做的指示。