using System; using System.Collections; using System.Configuration.Install; using System.ServiceProcess; namespace Vinno.FIS.Sonopost.Upgrade { public class ServiceHelper { private static string _serviceFilePath = $"{AppDomain.CurrentDomain.BaseDirectory}\\Vinno.FIS.Sonopost.Service.exe"; private static string _serviceName = "SonopostService"; /// /// 安装服务 /// public static void Install() { if (IsServiceExisted(_serviceName)) { UnInstall(); } InstallService(_serviceFilePath); } /// /// 卸载服务 /// public static void UnInstall() { if (IsServiceExisted(_serviceName)) { ServiceStop(_serviceName); UninstallService(_serviceFilePath); } } /// /// 启动服务 /// public static void Start() { if (IsServiceExisted(_serviceName)) { ServiceStart(_serviceName); } } /// /// 停止服务 /// public static void Stop() { if (IsServiceExisted(_serviceName)) { ServiceStop(_serviceName); } } /// /// 服务是否已经启动 /// /// /// public static bool IsServiceStarted(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { return control.Status == ServiceControllerStatus.Running; } } private static bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } private static void InstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; IDictionary savedState = new Hashtable(); installer.Install(savedState); installer.Commit(savedState); } } private static void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } private static void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); control.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } } } private static void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); control.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } } } } }