C#启动停止windows服务

来源:互联网 发布:linux 串口驱动 编辑:程序博客网 时间:2024/05/16 14:11

 

启动windows服务:

引用命名空间using System.ServiceProcess;

  ServiceController cs1 = new ServiceController();  //建立服务对象
   cs1.MachineName = "localhost";
   cs1.ServiceName =  servicename;  // 服务名称

// 服务 停止则运行
   if (cs1.Status == ServiceControllerStatus.Stopped
                || cs1.Status == ServiceControllerStatus.StopPending)
     {
              cs1.Start();
              cs1.Refresh();
      }

 

相应的,服务运行的情况下也可以停止服务。

            if (cs1.Status == ServiceControllerStatus.Running)
            {
                cs1.Stop();
                cs1.Refresh();
            }

原创粉丝点击