C#安装/卸载/启用windows服务

今天遇到了一个小需求,就是使用C#编写的windows服务,需要在程序内进行安装、卸载、启用、关闭,以此来使安装windows服务的门槛变低,具体核心代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class ServiceHelper
    {
        #region 服务是否存在
        /// <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;
        }
        #endregion

        #region 启动服务
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName">服务名</param>
        public static void StartService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                //判断服务状态
                if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                {
                    try
                    {
                        service.Start(); //启动服务
                        for (int i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            Thread.Sleep(1000);
                            if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running) //判断服务是否正常运行
                            {
                                break;
                            }
                            if (i == 59)
                            {
                                Console.WriteLine("启动服务失败:" + serviceName, null);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("启动服务失败:" + ex.Message, ex);
                    }

                }
            }
        }
        #endregion

        #region 停止服务
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName">服务名</param>
        public static void StopService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                //判断服务状态
                if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running)
                {
                    try
                    {
                        if (service.CanStop)
                        {
                            // 如果权限不够是不能Stop()的。
                            service.Stop();
                            // 这句话如果没有对该服务的后续操作可以不要,C#程序只是以权限向操作系统发出关闭某服务的消息而已,真正关闭该服务的是操作系统而非此C#程序(下面的Start的也一样)
                            service.WaitForStatus(ServiceControllerStatus.Stopped);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("停止服务失败:" + ex.Message, ex);
                    }
                }
            }
        }
        #endregion

        #region 获取服务状态
        /// <summary>
        /// 获取服务状态
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <returns></returns>
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            return service.Status;
        }
        #endregion

        #region 配置服务(安装和卸载)
        /// <summary>
        /// 配置服务(安装和卸载)
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <param name="install">是否安装,true安装,false 卸载</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 = "测试服务安装",
                StartType = ServiceStartMode.Automatic//运行方式
            });
            ti.Context = new InstallContext();
            ti.Context.Parameters["assemblypath"] = Assembly.GetEntryAssembly().Location.Replace(Assembly.GetExecutingAssembly().GetName().Name.ToString() + ".exe", "") + serviceName;
            if (install) //是否安装服务
            {
                ti.Install(new Hashtable());
            }
            else
            {
                ti.Uninstall(null);
            }
        }
        #endregion



    }
}

调用代码如下:

using ConsoleApp1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static string ServiceName = "EuSoft.TrackingService.exe";

        static void Main(string[] args)
        {

            if (args.Length > 0)
            {

                //带参启动运行服务

                //try
                //{
                //    ServiceBase[] serviceToRun = new ServiceBase[] { new ServiceInit() };
                //    ServiceBase.Run(serviceToRun);
                //}
                //catch (Exception ex)
                //{

                //}

                //不带参启动配置程序   
            }
            else
            {
                ServiceInstallWindow();
            }

            Console.ReadKey();

        }


        /// <summary>
        /// 启动安装服务界面
        /// </summary>
        static void ServiceInstallWindow()
        {
            while (true)
            {
                Console.WriteLine("————————————————————");
                Console.WriteLine("请选择你要执行的操作:");
                Console.WriteLine("1运行服务");
                Console.WriteLine("2停止服务");
                Console.WriteLine("3安装服务");
                Console.WriteLine("4卸载服务");
                Console.WriteLine("5验证服务状态");
                Console.WriteLine("6退出");
                Console.WriteLine("————————————————————");

                char keyChar = Console.ReadKey().KeyChar;

                //运行服务
                if (keyChar == '1')
                {
                    Console.WriteLine("服务已启动,请稍后......");
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.StartService(ServiceName);
                        Console.WriteLine("服务已启动!");
                    }
                    else
                    {
                        Console.WriteLine("服务不存在......");
                    }
                }
                //停止服务
                if (keyChar == '2')
                {
                    Console.WriteLine("服务正在停止,请稍后......");
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.StopService(ServiceName);
                        Console.WriteLine("服务已停止!");
                    }
                    else
                    {
                        Console.WriteLine("服务不存在......");
                    }
                }
                //安装服务
                else if (keyChar == '3')
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, true);
                    }
                    else
                    {
                        Console.WriteLine("服务已存在......");
                    }
                }
                //卸载服务
                else if (keyChar == '4')
                {
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, false);
                    }
                    else
                    {
                        Console.WriteLine("服务不存在......");
                    }
                }
                //验证服务
                else if (keyChar == '5')
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        Console.WriteLine("服务不存在......");
                    }
                    else
                    {
                        Console.WriteLine("服务状态:" + ServiceHelper.GetServiceStatus(ServiceName).ToString());
                    }
                }
                //退出
                else if (keyChar == '6')
                {
                    break;
                }
                else
                {
                    Console.WriteLine("请输入一个有效键!");
                    Console.WriteLine("————————————————————");
                }
            }
        }

    }
}

注:启动服务好像有点问题,可能是我服务写的有问题,应该不是安装和启动方式的问题。

THE END