c# Windows服务管理

.NET Framework中提供的类库可以很方便的实现对windows服务的安装、卸载、启动、停止、获取运行状态等功能。这些类都在System.ServiceProcess命名空间下。

所以,在开始编写程序之前,需要先引用System.ServiceProcess。

获取Windows服务列表:

// 获取服务列表
ServiceController[] serviceList = ServiceController.GetServices();
// 按名称排序
serviceList = serviceList.OrderBy(m => m.DisplayName).ToArray();
// 遍历服务列表
foreach (ServiceController sc in serviceList)
{
    // 服务信息
}

启动服务:

string serviceName="服务名称";
ServiceController sc = new ServiceController(serviceName); //建立服务对象
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
    sc.Start();
    sc.WaitForStatus(ServiceControllerStatus.Running); //等待启动
    sc.Refresh();
}

停止服务:

string serverName="服务名称";
ServiceController sc = new ServiceController(serviceName); //建立服务对象
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
    sc.Stop();
    sc.WaitForStatus(ServiceControllerStatus.Stopped);  //等待停止
    sc.Refresh();
}

重启服务:

string serviceName = "服务名称";
ServiceController sc = new ServiceController(serviceName); //建立服务对象
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
    sc.Stop();
    sc.WaitForStatus(ServiceControllerStatus.Stopped);  //等待停止
    sc.Refresh();
}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running); //等待启动
sc.Refresh();

 

posted @ 2019-08-12 17:20  薄心之心  阅读(852)  评论(0编辑  收藏  举报