Installing Windows Service programmatically

后端 未结 4 1643
Happy的楠姐
Happy的楠姐 2020-12-02 06:43

How do I install a Windows Service programmatically without using installutil.exe?

4条回答
  •  天涯浪人
    2020-12-02 07:05

    You can install the service by adding this code (in the program file, Program.cs) to install itself when run from the commandline using specified parameters:

    /// 
            /// The main entry point for the application.
            /// 
            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);
                }
            }
    

提交回复
热议问题