using System; using System.Collections.Generic; using System.ServiceProcess; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using COMMON; namespace SERVER.LIB { public class TestingServices { public static object lockers = new object(); /// /// 检测本机指定服务 仅仅 windows /// /// 0 只是返回状态 1 启动 2 重启 3 停止 /// 名字 /// 0 不存在 2 未运行 1 已经运行 public static int ISok(string name = "", int type = 0) { try { #region RuntimeInformation.IsOSPlatform(OSPlatform.Windows) //获取指定服务,若服务状态不是Runing就Start该服务 #pragma warning disable CA1416 // 验证平台兼容性 var server = ServiceController.GetServices().FirstOrDefault(service => service.ServiceName == name); if (server == null) { return 0; } if (type != 0) { lock (lockers) { string path = Directory.GetCurrentDirectory() + "\\App_Data\\Server"; Directory.CreateDirectory(path); switch (type) { case 1: if (server.Status != ServiceControllerStatus.Running) { File.WriteAllText(path + "\\Server.xcljj", type.ToString()); } break; case 2: File.WriteAllText(path + "\\Server.xcljj", type.ToString()); break; case 3: File.WriteAllText(path + "\\Server.xcljj", type.ToString()); break; } } } //开启后再检测一次 return type != 0 ? ISok() : (server.Status == ServiceControllerStatus.Running ? 1 : 2); #endregion } catch (Exception ex) { LogHelp.Error("服务操作失败!" + ex.ToString()); return 0; } } } }