C#检验Windows Service是否存在和启动

检验某个Service是否存在:

using System;
using System.ServiceProcess;
using System.Windows.Forms;

private static bool IsExistSqlServer(string serviceName)
        {
            bool result = false;
            ServiceController[] controllers = ServiceController.GetServices();
            int nNum = controllers.Length;
            try
            {
                for (int i = 0; i <= (nNum - 1); i++)
                {
                    if ((controllers[i].ServiceName.ToUpper() == serviceName.ToUpper()))
                    {
                        result = true;
                        break;
                    }
                }
            }
            catch(Exception e)
            {
                Helper.Write(e.Message);
                result = false;
            }
            return result;
        }

其中:类ServiceController的说明:

表示 Windows 服务并允许连接到正在运行或者已停止的服务、对其进行操作或获取有关它的信息。

public static ServiceController[] GetDevices(string machineName)

说明: 检索本地计算机上的所有服务(设备驱动程序服务除外)。 返回结果: System.ServiceProcess.ServiceController 类型的数组,其中每个元素均与本地计算机上的一个服务关联。

启动一个Windows服务

 1  private static bool IsStartService(string serviceName)
 2         {
 3             ServiceController[] controllers = ServiceController.GetServices();
 4             int nNum = controllers.Length;
 5             try
 6             {
 7                 for (int i = 0; i <= (nNum - 1); i++)
 8                 {
 9                     Application.DoEvents();
10                     if ((controllers[i].ServiceName.ToUpper() == serviceName.ToUpper()))
11                     {
12                         if ((controllers[i].Status != ServiceControllerStatus.Running))
13                         {
14                             if ((controllers[i].Status != ServiceControllerStatus.Running))
15                             {
16                                 controllers[i].Start();
17                             }
18                             controllers[i].WaitForStatus(ServiceControllerStatus.Running);
19                         }
20                         return true;
21                     }
22                 }
23                 return true;
24             }
25             catch(Exception e)
26             {
27                 Helper.Write(e.Message);
28                 return false;
29             }
30         }

其中:

public void Start() --启动服务,不传递任何参数。

WaitForStatus:无休止的等待服务达到指定状态。
原文地址:https://www.cnblogs.com/qinlixue/p/2913578.html