public ActionResult ListService() { //获取已经保存好的windows服务名称 IList<Model.ReportServicesInfoEnt> List =GetServiceNameList; ServiceController serviceObject = null; foreach (Model.ReportServicesInfoEnt e in List) { FileInfo fi= GetWindowsServiceInstallPath(e.ServiceName); if (fi != null) { e.FilePath = fi.FullName; serviceObject = GetServiceObject(e.ServiceName); if (serviceObject != null) { e.StatusName = serviceObject.Status.ToString(); } } } ViewData["Count"] = Count; ViewData["ReportServicesInfoEnt"] = List; return View(); } #region 服务操作 /// <summary> /// 服务操作 /// </summary> /// <param name="serviceName"></param> /// <param name="Type">5表示启动,10表示重启,15表示停止</param> /// <returns></returns> public ActionResult SetService(string serviceName, int SetType) { var msg = ""; switch (SetType) { case 5: msg = "启动"; break; case 10: msg = "重启"; break; case 15: msg = "停止"; break; } var ret = new { Success = true, Message = msg + "完成" }; return Json(ret, JsonRequestBehavior.AllowGet); } /// <summary> /// 获取windows服务实例 /// </summary> /// <param name="ServiceName"></param> /// <returns></returns> private ServiceController GetServiceObject(string ServiceName) { return new ServiceController(ServiceName); } /// <summary> /// 获取服务注册表信息 /// </summary> /// <param name="ServiceName"></param> /// <returns></returns> private FileInfo GetWindowsServiceInstallPath(string ServiceName) { string key = @"SYSTEMCurrentControlSetServices" + ServiceName; if (Registry.LocalMachine.OpenSubKey(key) == null) { return null; } else { string path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString(); path = path.Replace(""", string.Empty); FileInfo fi = new System.IO.FileInfo(path); return fi; } } /// <summary> /// 重启 /// </summary> /// <param name="sc"></param> private void ReStarService(ServiceController sc) { this.StopService(sc); this.StarService(sc); } /// <summary> /// 停止服务 /// </summary> /// <param name="sc"></param> private void StopService(ServiceController sc) { if ((sc.Status == ServiceControllerStatus.Paused) || (sc.Status == ServiceControllerStatus.Running)) { sc.Stop(); } } /// <summary> /// 开始服务 /// </summary> /// <param name="sc"></param> private void StarService(ServiceController sc) { if ((sc.Status == ServiceControllerStatus.Paused) || (sc.Status == ServiceControllerStatus.Stopped)) { sc.Start(); } } #endregion