C#通过SC命令和静态公共类来操作Windows服务
调用的Windows服务应用程序网址:http://www.cnblogs.com/pingming/p/5115304.html
一、引用
二、公共静态类:可以单独放到类库里
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Install; using System.Linq; using System.ServiceProcess; using System.Text; using Microsoft.Win32; namespace CM.Web.UI { public static class WindowsServiceHelper { #region 已封装Window服务 /// <summary> /// 安装服务 /// </summary> /// <param name="NameService">Windows服务显示名称</param> /// <returns>存在返回 true,否则返回 false;</returns> public static bool InstallService(string serviceName) { bool flag = true; if (!IsServiceIsExisted(serviceName)) { try { string location = System.Reflection.Assembly.GetExecutingAssembly().Location; string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + serviceName + ".exe"; //测试用的绝对路径 //string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe"; InstallMyService(null, serviceFileName); } catch { flag = false; } } return flag; } /// <summary> /// 卸载服务 /// </summary> /// <param name="NameService">Windows服务显示名称</param> /// <returns>存在返回 true,否则返回 false;</returns> public static bool UninstallService(string serviceName) { bool flag = true; if (IsServiceIsExisted(serviceName)) { try { string location = System.Reflection.Assembly.GetExecutingAssembly().Location; string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + serviceName + ".exe"; //测试用的绝对路径 //string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe"; UnInstallMyService(serviceFileName); } catch { flag = false; } } return flag; } /// <summary> /// 检查Windows服务是否存在 /// </summary> /// <param name="NameService">Windows服务显示名称</param> /// <returns>存在返回 true,否则返回 false;</returns> public static bool IsServiceIsExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } /// <summary> /// 安装Windows服务 /// </summary> /// <param name="stateSaver">集合</param> /// <param name="filepath">Windows服务程序文件路径</param> private static void InstallMyService(IDictionary stateSaver, string filePath) { AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller(); AssemblyInstaller1.UseNewContext = true; AssemblyInstaller1.Path = filePath; AssemblyInstaller1.Install(stateSaver); AssemblyInstaller1.Commit(stateSaver); AssemblyInstaller1.Dispose(); } /// <summary> /// 卸载Windows服务 /// </summary> /// <param name="filePath">Windows服务程序文件路径</param> private static void UnInstallMyService(string filePath) { AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller(); AssemblyInstaller1.UseNewContext = true; AssemblyInstaller1.Path = filePath; AssemblyInstaller1.Uninstall(null); AssemblyInstaller1.Dispose(); } /// <summary> /// 判断某个Windows服务是否启动 /// </summary> /// <param name="serviceName">Windows服务显示名称</param> /// <returns>bool</returns> public static bool IsServiceStart(string serviceName) { ServiceController psc = new ServiceController(serviceName); bool bStartStatus = false; try { if (!psc.Status.Equals(ServiceControllerStatus.Stopped)) { bStartStatus = true; } return bStartStatus; } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 修改服务的启动项 2为自动,3为手动 /// </summary> /// <param name="startType">2为自动,3为手动</param> /// <param name="serviceName">Windows服务显示名称</param> /// <returns>bool</returns> public static bool ChangeServiceStartType(int startType, string serviceName) { try { RegistryKey regist = Registry.LocalMachine; RegistryKey sysReg = regist.OpenSubKey("SYSTEM"); RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet"); RegistryKey services = currentControlSet.OpenSubKey("Services"); RegistryKey servicesName = services.OpenSubKey(serviceName, true); servicesName.SetValue("Start", startType); } catch (Exception ex) { return false; } return true; } /// <summary> /// 启动服务 /// </summary> /// <param name="serviceName">Windows服务显示名称</param> /// <returns>bool</returns> public static bool StartService(string serviceName) { bool flag = true; if (IsServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { flag = false; } } } } return flag; } /// <summary> /// 停止服务 /// </summary> /// <param name="serviceName">Windows服务显示名称</param> /// <returns>bool</returns> public static bool StopService(string serviceName) { bool flag = true; if (IsServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { break; } if (i == 59) { flag = false; } } } } return flag; } #endregion } }
三、静态公共类操作Windows服务-------控制台程序
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Install; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace ConsoleService { class Program { static void Main(string[] args) { Console.WriteLine("Window服务应用程序"); Console.WriteLine("请选择,[1]安装服务 [2]卸载服务 [3]启动服务 [4]关闭服务 [5]暂停/继续 [6]检测服务"); var rs = int.Parse(Console.ReadLine()); //一、通过封装类操作Windows服务 switch (rs) { case 1://安装服务 InstallService("ServiceDemo"); Console.WriteLine("安装成功"); break; case 2://卸载服务 UninstallService("ServiceDemo"); Console.WriteLine("卸载成功"); break; case 3://启动服务 StartService("ServiceDemo"); Console.WriteLine("启动服务成功"); break; case 4://关闭服务 StopService("ServiceDemo"); Console.WriteLine("关闭服务成功"); break; case 5://暂停/继续 ServiceController serviceControllerPauseToContinue = new ServiceController("KJLMDemo"); if (serviceControllerPauseToContinue.CanPauseAndContinue) { if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Running) serviceControllerPauseToContinue.Pause(); else if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Paused) serviceControllerPauseToContinue.Continue(); } break; case 6://判断服务是否开启 Console.WriteLine("服务状态:" + IsServiceStart("ServiceDemo")); break; default: break; } Console.ReadKey(); } } }
四、通过SC命令操作Windows服务-------控制台程序
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Install; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace ConsoleService { class Program { static void Main(string[] args) { Console.WriteLine("Window服务应用程序"); Console.WriteLine("请选择,[1]安装服务 [2]卸载服务 [3]启动服务 [4]关闭服务 [5]暂停/继续 [6]检测服务"); var rs = int.Parse(Console.ReadLine());
//二、通过SC命令操作Windows服务 switch (rs) { case 1://安装服务 //取当前服务的路径bin/debug下面的exe文件 string path = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe"; Process.Start("sc", "create KJLMDemo binPath= \"" + path + "\" "); Console.WriteLine("安装成功"); break; case 2://卸载服务 Process.Start("sc", "delete KJLMDemo"); Console.WriteLine("卸载成功"); break; case 3://启动服务 ServiceController serviceControllerStart = new ServiceController("KJLMDemo"); serviceControllerStart.Start(); Console.WriteLine("启动服务成功"); break; case 4://关闭服务 ServiceController serviceControllerStop = new ServiceController("KJLMDemo"); serviceControllerStop.Stop(); Console.WriteLine("关闭服务成功"); break; case 5://暂停/继续 ServiceController serviceControllerPauseToContinue = new ServiceController("KJLMDemo"); if (serviceControllerPauseToContinue.CanPauseAndContinue) { if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Running) serviceControllerPauseToContinue.Pause(); else if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Paused) serviceControllerPauseToContinue.Continue(); } break; case 6://判断服务是否开启 ServiceController serviceControllerIsEnabled = new ServiceController("KJLMDemo"); string Status = serviceControllerIsEnabled.Status.ToString(); Console.WriteLine("服务状态:"+Status); break; default: break; } } }