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();}