C# 註冊Windows服務

坤机嘎嘎嘎發表於2024-11-19

環境:.NET Farmework 4.7.2

IDE:Visual Studio 2022

新增程式集引用:

System.ServiceProcess

System.Configuration.Install

右鍵專案,新增UpdateServices1類,讓UpdateServices1繼承ServiceBase(UpdateServices1換成自己的Services服務)

編譯過後如果需要更新服務程式碼,要在Windows服務裡面先停止

C# 註冊Windows服務
const string ServiceName = "ClientUpdateServices";
        const string ServiceDescription = "服務描述";
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                try
                {
                    ServiceBase[] serviceToRun = new ServiceBase[] { new UpdateServices1() };
                    ServiceBase.Run(serviceToRun);
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
            StartLable:
                Console.WriteLine("請選擇你要執行的操作——1:自動部署服務(Q),2:安裝服務(W),3:解除安裝服務(E),4:驗證服務狀態(R),5:退出(T)");
                Console.WriteLine("————————————————————");
                ConsoleKey key = Console.ReadKey().Key;
                string conkey = Console.ReadLine();
                ServiceHelper.SetServicesDesc(ServiceDescription);
                if (key == ConsoleKey.NumPad1 || key == ConsoleKey.D1 || key == ConsoleKey.Q || conkey == "1")
                {
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, false);
                    }
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, true);
                    }
                    ServiceHelper.StartService(ServiceName);
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad2 || key == ConsoleKey.D2 || key == ConsoleKey.W || conkey == "2")
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, true);
                    }
                    else
                    {
                        Console.WriteLine("\n服務已存在......");
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad3 || key == ConsoleKey.D3 || key == ConsoleKey.E || conkey == "3")
                {
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, false);
                    }
                    else
                    {
                        Console.WriteLine("\n服務不存在......");
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad4 || key == ConsoleKey.D4 || key == ConsoleKey.R || conkey == "4")
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        Console.WriteLine("\n服務不存在......");
                    }
                    else
                    {
                        Console.WriteLine("\n服務狀態:" + ServiceHelper.GetServiceStatus(ServiceName).ToString());
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad5 || key == ConsoleKey.D5 || key == ConsoleKey.T || conkey == "5") { }
                else
                {
                    Console.WriteLine("\n請輸入一個有效鍵!");
                    Console.WriteLine("————————————————————");
                    goto StartLable;
                }
            }
        }
Program

C# 註冊Windows服務
public static class ServiceHelper
    {
        static string ServiceDescription = "";

        public static void SetServicesDesc(string serviceDesc)
        {
            ServiceDescription = serviceDesc;
        }

        /// <summary>
        /// 服務是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StartService(string serviceName)
        {
            if (IsServiceExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running &&
                    service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception("Start Service Error:" + serviceName);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 獲取服務狀態
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
            return service.Status;
        }

        /// <summary>
        /// 配置服務
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="install"></param>
        public static void ConfigService(string serviceName, bool install)
        {
            TransactedInstaller ti = new TransactedInstaller();
            ti.Installers.Add(new ServiceProcessInstaller
            {
                Account = ServiceAccount.LocalSystem
            });
            ti.Installers.Add(new ServiceInstaller
            {
                DisplayName = serviceName,
                ServiceName = serviceName,
                Description = ServiceDescription,
                StartType = ServiceStartMode.Automatic//執行方式
            });
            ti.Context = new InstallContext();
            ti.Context.Parameters["assemblypath"] = "\"" + Assembly.GetEntryAssembly().Location + "\" /service";
            if (install)
            {
                ti.Install(new Hashtable());
            }
            else
            {
                ti.Uninstall(null);
            }
        }
    }
ServiceHelper

相關文章