使用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服务。我们可以右键单击任意一个服务,然后对其进行相应的启动/停止/重启等操作,如图:
本文将向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.ServiceController
Nuget程序包,然后再调用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);
}
}
}
}
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2022-03-24 在管道中,应用程序池有两种运行模式:集成模式和经典模式。
2022-03-24 IntelliJ IDEA 2020最新注册码(亲测有效,可激活至 2089 年) 下载安装,选择免费使用30天,拖入jar包,自动重启Idea
2022-03-24 Notepad++使用技法
2022-03-24 Base64解码、Base64编码、Base64加密解密规则
2022-03-24 Maven安装与配置 JDK Eclipse Maven程序包
2022-03-24 Hibernate介绍及环境搭建 Hibernate与Mybatis区别
2022-03-24 IntelliJ IDEA 编辑窗口开多后自动关闭问题 Setting - Editor Tabs - Tab limit