使用C#编程实现获取所有Windows服务列表及对Windows服务(Windows Service)的启动/停止/重启的方法

C#开发 作者: Rector 79 次阅读 · 读完约需 2 分钟 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

前言

在Windows操作系统中,我们可以在命令提示符中运行servcies.msc打开Windows服务的窗口,这个窗口中会罗列出此操作系统中当前所有已安装的Windows服务。我们可以右键单击任意一个服务,然后对其进行相应的启动/停止/重启等操作,如图:

Windows服务列表

本文将向C#开发者们介绍如何使用编程实现获取所有Windows服务列表及对Windows服务(Windows Service)的启动/停止/重启的方法。

获取当前Windows操作系统所有的服务列表

在使用ServiceController之前,请引入命名空间:

using System.ServiceProcess;

获取当前Windows操作系统所有的服务列表的方法ServiceController.GetServices(),如下:

public static List<ServiceController> GetAllServices()
{
    return ServiceController.GetServices().ToList();
}

获取单个指定服务名称的Windows服务为:

public static ServiceController GetService(string serviceName)
{
    ServiceController[] services = ServiceController.GetServices();
    return services.FirstOrDefault(_ => _.ServiceName.ToLower() == serviceName.ToLower());
}

判断一个指定的服务是否正在运行:

public static bool IsServiceRunning(string serviceName)
{
    ServiceControllerStatus status;
    uint counter = 0;
    do
    {
        ServiceController service = GetService(serviceName);
        if (service == null)
        {
            return false;
        }

        Thread.Sleep(100);
        status = service.Status;
    } while (!(status == ServiceControllerStatus.Stopped ||
               status == ServiceControllerStatus.Running) &&
             (++counter < 30));
    return status == ServiceControllerStatus.Running;
}

判断一个指定的服务是否已安装:

public static bool IsServiceInstalled(string serviceName)
{
    return GetService(serviceName) != null;
}

启动一个指定名称的服务

public static void StartService(string serviceName)
{
    ServiceController controller = GetService(serviceName);
    if (controller == null)
    {
        return;
    }

    controller.Start();
    controller.WaitForStatus(ServiceControllerStatus.Running);
}

停止一个指定名称的服务

public static void StopService(string serviceName)
{
    ServiceController controller = GetService(serviceName);
    if (controller == null)
    {
        return;
    }

    controller.Stop();
    controller.WaitForStatus(ServiceControllerStatus.Stopped);
}

重启一个指定名称的服务

重启一个指定名称的服务需要首先找到服务,如果此服务正在运行,则需要停止,然后再启动服务,具体代码如下:

public static void RestartService(string serviceName)
{
    int timeoutMilliseconds = 50;
    ServiceController service = new ServiceController(serviceName);
    try
    {
        int millisec1 = 0;
        TimeSpan timeout;
        if (service.Status == ServiceControllerStatus.Running)
        {
            millisec1 = Environment.TickCount;
            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
        int millisec2 = Environment.TickCount;
        timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);

    }
    catch (Exception e)
    {
        //Trace.WriteLine(e.Message);
    }
}

总结

下面提供一个关于C#操作Windows服务的封装类,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Threading;

namespace ConsoleApp1
{
    public class ServiceManager
    {
        public static List<string> GetAllServiceName()
        {
            var serviceNameList = ServiceController.GetServices().Select(x => x.ServiceName);
            return serviceNameList.ToList();
        }

        public static List<ServiceController> GetAllServices()
        {
            return ServiceController.GetServices().ToList();
        }

        public static ServiceController GetService(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            return services.FirstOrDefault(_ => _.ServiceName.ToLower() == serviceName.ToLower());
        }

        public static bool IsServiceRunning(string serviceName)
        {
            ServiceControllerStatus status;
            uint counter = 0;
            do
            {
                ServiceController service = GetService(serviceName);
                if (service == null)
                {
                    return false;
                }

                Thread.Sleep(100);
                status = service.Status;
            } while (!(status == ServiceControllerStatus.Stopped ||
                       status == ServiceControllerStatus.Running) &&
                     (++counter < 30));
            return status == ServiceControllerStatus.Running;
        }

        public static bool IsServiceInstalled(string serviceName)
        {
            return GetService(serviceName) != null;
        }

        public static void StartService(string serviceName)
        {
            ServiceController controller = GetService(serviceName);
            if (controller == null)
            {
                return;
            }

            controller.Start();
            controller.WaitForStatus(ServiceControllerStatus.Running);
        }

        public static void StopService(string serviceName)
        {
            ServiceController controller = GetService(serviceName);
            if (controller == null)
            {
                return;
            }

            controller.Stop();
            controller.WaitForStatus(ServiceControllerStatus.Stopped);
        }

        public static void RestartService(string serviceName)
        {
            int timeoutMilliseconds = 50;
            ServiceController service = new ServiceController(serviceName);
            try
            {
                int millisec1 = 0;
                TimeSpan timeout;
                if (service.Status == ServiceControllerStatus.Running)
                {
                    millisec1 = Environment.TickCount;
                    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }
                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);

            }
            catch (Exception e)
            {
                //Trace.WriteLine(e.Message);
            }
        }
    }
}

阅读了该文章的人还浏览了...

本文永久链接码友网 » 使用C#编程实现获取所有Windows服务列表及对Windows服务(Windows Service)的启动/停止/重启的方法

发布于: 2019-06-18 14:04:18
分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册