zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    UVa 11538 Chess Queen (排列组合计数)
    CodeForces 730H Delete Them (暴力)
    CodeForces 730G Car Repair Shop (暴力)
    汇编(assembling)简介(源:阮一峰)
    CSS骚操作
    Jquery复习总结
    CGI与ISAPI的区别(转)
    SQL中Group By的使用(转)
    05 ADO.net
    04 SqlServer
  • 原文地址:https://www.cnblogs.com/bossing/p/11341368.html
Copyright © 2011-2022 走看看