/// <summary> /// 将服务设置为 自动启动,并启动未启动的服务 /// </summary> /// <param name="service"></param> public static void StartService(ServiceController service) { if (service == null) { return; } try { if (WinSrvHelper.GetStartupType(service) != "AUTOMATIC") { ChangeStartMode(service, ServiceStartMode.Automatic); // 将服务设置为 自动启动 } if (service.Status == ServiceControllerStatus.Running) // 已启动的服务不能再次启动 { return; } service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } catch (Exception ex) { NLogHelper.Error(ex); } }
/// <summary> /// 获取服务状态 /// </summary> /// <param name="serviceName"></param> /// <param name="status_chn">中文状态</param> /// <param name="status_eng">英文状态</param> public static void GetStatus(string serviceName, ref string status_chn, ref string status_eng) { ServiceController sc = WinSrvHelper.GetService(serviceName); if (sc == null) { status_eng = "Non exist"; status_chn = "服务不存在"; return; } sc.Refresh(); switch (sc.Status) { case ServiceControllerStatus.Running: status_eng = "Running"; status_chn = "已启动"; break; case ServiceControllerStatus.Stopped: status_eng = "Stopped"; status_chn = "已停止"; break; case ServiceControllerStatus.Paused: status_eng = "Paused"; status_chn = "已暂停"; break; case ServiceControllerStatus.StopPending: status_eng = "Stopping"; status_chn = "停止中..."; break; case ServiceControllerStatus.StartPending: status_eng = "Starting"; status_chn = "启动中..."; break; default: status_eng = "Status Changing"; status_chn = "获取中..."; break; } }
public static void SafeChangeStartMode(string serviceName, ServiceStartMode mode) { ServiceController service = GetService(serviceName); if (service == null) { return; } string strMode = mode.ToString().ToUpper().TrimStart("SERVICESTARTMODE."); try { if (WinSrvHelper.GetStartupType(service) != strMode) { ChangeStartMode(service, mode); // 将服务设置为 自动启动 } } catch (Exception ex) { NLogHelper.Error(ex); } }