rfcd12 发表于 2014-1-22 10:56:11

Windows Service的安装卸载 和 Service控制

本文内容包括如何通过C#代码安装Windows Service(exe文件,并非打包后的安装文件)、判断Service是否存在、获得Service状态及启动停止Service。

  创建Windows Service项目并Build得到exe文件,如何创建 Service 可参考 创建windows service 并打包成安装文件。

一、 Windows服务的安装和卸载

  安装和卸载服务可以使用 .NET 工具installutil.exe (eg:安装-> installutil xxx.exe 卸载-> installutil /u xxx.exe),使用ManagedInstallerClass可以实现安装卸载Windows 服务,ManagedInstallerClass 在System.Configuration.Install命名空间下。
/// <summary>
      /// 使用Windows Service对应的exe文件 安装Service
      /// 和 installutil xxx.exe 效果相同
      /// </summary>
      /// <param name="installFile">exe文件(包含路径)</param>
      /// <returns>是否安装成功</returns>
      public static bool InstallServie(string installFile)
      {
            string[] args = { installFile };
            try
            {
                ManagedInstallerClass.InstallHelper(args);
                return true;
            }
            catch
            {
                return false;
            }
      }

      /// <summary>
      /// 使用Windows Service对应的exe文件 卸载Service
      /// 和 installutil /u xxx.exe 效果相同
      /// </summary>
      /// <param name="installFile">exe文件(包含路径)</param>
      /// <returns>是否卸载成功</returns>
      public static bool UninstallService(string installFile)
      {
            string[] args = { "/u", installFile };
            try
            {
                // 根据文件获得服务名,假设exe文件名和服务名相同
                string tmp = installFile;
                if (tmp.IndexOf('\\') != -1)
                {
                  tmp = tmp.Substring(tmp.LastIndexOf('\\') + 1);
                }
                string svcName = tmp.Substring(0, tmp.LastIndexOf('.'));
                // 在卸载服务之前 要先停止windows服务
                StopService(svcName);

                ManagedInstallerClass.InstallHelper(args);
                return true;
            }
            catch
            {
                return false;
            }
      }注意: 服务删除前需要先停止服务,否则服务被标记为禁用,并无法删除。原因:系统删除服务时,首先是标记服务为“删除”,等待服务的所有引用完全断开后,服务才被完全删除。当服务引用未完全断开时,就删除服务,系统将服务锁死为“禁用”状态,并禁止其他操作,注意此时服务尚未完全删除。所以对已删除后立即重装的服务,需要完全释放与服务相关的所有引用,此时系统才真正完全删除服务,之后才能再次安装服务。如果出现服务禁用问题,检查代码,哪些地方有服务引用,同时检查是否其他程序还在引用,也要终止这些引用程序。
二、Windows服务的状态获取和控制
  使用ServiceController来获取服务状态或对服务进行控制。
  ServiceController 表示 Windows 服务并允许连接到正在运行或者已停止的服务、对其进行操作或获取有关它的信息。使用 ServiceController 类连接到现有服务并控制其行为。当创建 ServiceController 类的实例时,设置其属性,以便它与特定的 Windows 服务交互作用。然后可以使用此类来启动、停止和以其他方式操作该服务。创建实例后,必须为其设置两个属性来标识与其交互的服务:计算机名称和要控制的服务的名称。默认情况下,MachineName 设置为本地计算机,因此不需要更改它,除非想将该实例设置为指向另一台计算机。
  服务可以处理的命令集取决于该服务的属性;例如,可以将服务的 CanStop 属性设置为 false。该设置使 Stop 命令在那个特定的服务上不可用;它禁用了必要的按钮,使您无法从 SCM 中停止服务。如果试图通过代码停止服务,系统将引发错误,并显示错误信息“未能停止 servicename”。
常用操作如下:
  1.获得Service对应的ServiceController实例/// <summary>
      /// 获得service对应的ServiceController对象
      /// </summary>
      /// <param name="serviceName">服务名</param>
      /// <returns>ServiceController对象,若没有该服务,则返回null</returns>
      public static ServiceController GetService(string serviceName)
      {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                  return s;
                }
            }
            return null;
      }2.检查指定的服务是否存在
/// <summary>
      /// 检查指定的服务是否存在。
      /// </summary>
      /// <param name="serviceName">要查找的服务名字</param>
      /// <returns>是否存在</returns>
      public static bool ServiceExisted(string serviceName)
      {
            if (GetService(serviceName) == null)
            {
                return false;
            }
            else
            {
                return true;
            }
      } 3. 获得服务详细信息/// <summary>
      /// 获得Service的详细信息
      /// </summary>
      /// <param name="serviceName">服务名</param>
      /// <returns>Service信息,保存在string中</returns>
      public static string GetServiceInfo(string serviceName)
      {
            StringBuilder details = new StringBuilder();

            ServiceController sc = GetService(serviceName);

            if (sc == null)
            {
                return string.Format("{0} 不存在!", serviceName);
            }

            details.AppendLine(string.Format("服务标识的名称: {0}", sc.ServiceName));
            details.AppendLine(string.Format("服务友好名称:{0}", sc.DisplayName));
            details.AppendLine(string.Format("服务在启动后是否可以停止: {0}", sc.CanStop));
            details.AppendLine(string.Format("服务所驻留的计算机的名称: {0}", sc.MachineName)); // "." 表示本地计算机
            details.AppendLine(string.Format("服务类型: {0}", sc.ServiceType.ToString()));
            details.AppendLine(string.Format("服务状态: {0}", sc.Status.ToString()));

            // DependentServices 获取依赖于与此 ServiceController 实例关联的服务的服务集。
            StringBuilder dependentServices = new StringBuilder();
            foreach (ServiceController s in sc.DependentServices)
            {
                dependentServices.Append(s.ServiceName + ", ");
            }
            details.AppendLine(string.Format("依赖于与此 ServiceController 实例关联的服务的服务: {0}", dependentServices.ToString()));
            
            // ServicesDependedOn 此服务所依赖的服务集。
            StringBuilder serviceDependedOn = new StringBuilder();
            foreach (ServiceController s in sc.ServicesDependedOn)
            {
                serviceDependedOn.Append(s.ServiceName + ", ");
            }
            details.AppendLine(string.Format("此服务所依赖的服务: {0}", serviceDependedOn.ToString()));

            return details.ToString();
      } 4.启动服务
/// <summary>
      /// 启动服务
      /// </summary>
      /// <param name="serviceName">服务名</param>
      /// <returns>是否启动成功</returns>
      public static bool StartService(string serviceName)
      {
            ServiceController sc = GetService(serviceName);

            if (sc.Status != ServiceControllerStatus.Running)
            {
                try
                {
                  sc.Start();
                  sc.WaitForStatus(ServiceControllerStatus.Running);// 等待服务达到指定状态
                }
                catch
                {
                  return false;
                }
            }

            return true;
      } 5.停止服务/// <summary>
      /// 停止服务
      /// </summary>
      /// <param name="serviceName">服务名</param>
      /// <returns>是否停止服务成功,如果服务启动后不可以停止,则抛异常</returns>
      public static bool StopService(string serviceName)
      {
            ServiceController sc = GetService(serviceName);

            if (!sc.CanStop)
            {
                throw new Exception(string.Format("服务{0}启动后不可以停止.", serviceName));
            }

            if (sc.Status != ServiceControllerStatus.Stopped)
            {
                try
                {
                  sc.Stop();
                  sc.WaitForStatus(ServiceControllerStatus.Stopped);// 等待服务达到指定状态
                }
                catch
                {
                  return false;
                }
            }

            return true;
      }


页: [1]
查看完整版本: Windows Service的安装卸载 和 Service控制