首页 > 系统相关 >使用C#&.NET Core编程实现获取所有Windows服务列表及对Windows服务(Windows Service)的启动/停止/重启的方法

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

时间:2023-03-24 11:45:42浏览次数:48  
标签:Core Service service Windows static serviceName ServiceController ServiceControl

使用C#&.NET Core编程实现获取所有Windows服务列表及对Windows服务(Windows Service)的启动/停止/重启的方法
原文链接:https://codedefault.com/p/start-stop-restart-install-uninstall-windows-service-in-csharp-application

前言

在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);
    }
}

.NET Core程序获取Windows服务列表

如果是以.NET Core的程序中,请安装System.ServiceProcess.ServiceControllerNuget程序包,然后再调用ServiceController.GetServices()方法读取所有的Windows服务列表,示例如下:

        登录后复制
        
            
        
     using System.ServiceProcess;
Run();
Console.ReadKey();
static void Run()
{
    var services = ServiceController.GetServices();
    Console.WriteLine("Windows Services:");
    foreach (var service in services)
    {
        Console.WriteLine($"Name:{service.ServiceName}==>{service.Status.ToString()}");
    }
}

总结

下面提供一个关于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);
            }
        }
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

1

标签:Core,Service,service,Windows,static,serviceName,ServiceController,ServiceControl
From: https://www.cnblogs.com/sunny3158/p/17250989.html

相关文章

  • 在aspnetcore中实现AOP的方式
    aaspnetcore开发框架中实现aop不仅仅在业务上,在代码的优雅简洁和架构的稳定上都有着至关重要。下面介绍三种用过的。 第一种使用DispatchProxy实现通过使用System.Re......
  • 什么时候用ExecutorService,什么时候用ThreadPoolExecutor?
    如果不需要对线程池参数应用任何自定义微调,并且希望使用预配置的线程池实例,则应该选择ExecutorService。ExecutorService提供了几种方法来创建不同类型的线程池,例如固定的......
  • aspnetcore中aop的实现
    aaspnetcore开发框架中实现aop不仅仅在业务上,在代码的优雅简洁和架构的稳定上都有着至关重要。下面介绍三种用过的。 第一种通过System.Reflection的DispatchProxy类来......
  • windows下获取上传文件hash值
    执行命令:certutil-hashfileD:\test.txt   ......
  • DLL注入-Windows消息钩取
    0x01钩子钩子,英文Hook,泛指钓取所需东西而使用的一切工具。后来延伸为“偷看或截取信息时所用的手段或工具”。挂钩:为了偷看或截取来往信息而在中间设置岗哨的行为钩取......
  • Java多线程之ExecutorCompletionService
    目录1ExecutorCompletionService1.1简介1.2原理1.3Demo示例1.3.1未使用ExecutorCompletionService1.3.2使用ExecutorCompletionService1.4深入分析说明1.4.1所有方......
  • .net core 关于对swagger的UI(Index.html)或接口的权限验证;
    背景:如何在ASP.NetCore的生产环境中保护swaggerui,也就是index.html页面。其实swagger是自带禁用的功能的,只需要设置开关即可。但是有一些场景,是需要把这些接口进行开放......
  • 28、服务发现-CoreDNS、会话粘滞、无头服务
    1、基础知识1.1、需求在传统的系统部署中,服务运行在一个固定的已知的IP和端口上,如果一个服务需要调用另外一个服务,可以通过地址直接调用,但是,在虚拟化或容器话的环境......
  • Asp.net Core 全局异常处理
    中间件方式建立中间件处理类Startup.cs中注册任何Controller中的Action抛出异常均可被捕捉在项目根目录下自建目录Middleware新建中间件类ErrorHandlerMiddleware......
  • 200行代码,7个对象——让你了解ASP.NET Core框架的本质
    200行代码,7个对象——让你了解ASP.NETCore框架的本质原文还有源码下载和pdf格式的ppt下载。Toinstallmissingframework,download:https://aka.ms/dotnet-core-appla......