使用ServiceController控制windows服务
1.引用System.ServiceProcess命名空间
using System.ServiceProcess;
2.声明ServiceController变量
private ServiceController _controller;
3.假设服务名为ServicesName, 编写开始服务,停止服务,重启服务的代码如下
private void StopService() { this._controller = new ServiceController("ServicesName"); this._controller.Stop(); this._controller.WaitForStatus(ServiceControllerStatus.Stopped); this._controller.Close(); } private void StartService() { this._controller = new ServiceController("ServicesName"); this._controller.Start(); this._controller.WaitForStatus(ServiceControllerStatus.Running); this._controller.Close(); } private void ResetService() { this._controller = new ServiceController("ServicesName"); this._controller.Stop(); this._controller.WaitForStatus(ServiceControllerStatus.Stopped); this._controller.Start(); this._controller.WaitForStatus(ServiceControllerStatus.Running); this._controller.Close(); }