System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("FaceService"); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); //FaceService是服務的名字
補充記錄:markdown
/// <summary> /// 卸載Windows服務 /// </summary> /// <param name="filepath">程序文件路徑</param> public static void UnInstallmyService(string filepath) { try { AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller(); AssemblyInstaller1.UseNewContext = true; AssemblyInstaller1.Path = filepath; AssemblyInstaller1.Uninstall(null); AssemblyInstaller1.Dispose(); } catch (Exception e) { LOG.Logs.PutLog("卸載Windows服務時:" + e.Message); } }
/// <summary> /// 安裝Windows服務 /// </summary> /// <param name="stateSaver">集合</param> /// <param name="filepath">程序文件路徑</param> public static void InstallmyService(IDictionary stateSaver, string filepath) { try { AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller { UseNewContext = true, Path = filepath }; AssemblyInstaller1.Install(stateSaver); AssemblyInstaller1.Commit(stateSaver); AssemblyInstaller1.Dispose(); } catch (Exception e) { LOG.Logs.PutLog("安裝Windows服務時:" + e.Message); } }
/// <summary> /// 檢查服務存在的存在性 /// </summary> /// <param name=" NameService ">服務名</param> /// <returns>存在返回 true,不然返回 false;</returns> public static bool IsServiceExisted(string NameService) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName.ToLower() == NameService.ToLower()) { return true; } } } catch (Exception e) { LOG.Logs.PutLog("IsServiceExisted時:" + e.Message); } return false; }
/// <summary> /// 啓動服務 /// </summary> /// <param name="serviceName">服務名字</param> public static void ServiceStart(string serviceName) { try { if (IsServiceExisted(serviceName))//若是服務存在 { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start();//開啓被中止的服務 } } } } catch (Exception e) { LOG.Logs.PutLog("啓動服務時" + e.Message); } }