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