網上不少建立Widows Service 的方法,其安裝和運行服務的方式大可能是經過cmd 命令來實現的,這裏將經過控制檯的形式實現安裝、運行和卸載服務。spa
主頁代碼:操作系統
1 using KQService.Job; 2 using KQService.Utils; 3 using System; 4 using System.Collections.Generic; 5 using System.Configuration; 6 using System.Linq; 7 using System.ServiceProcess; 8 using System.Text; 9 using System.Threading.Tasks; 10 11 namespace KQService.WS 12 { 13 static class Program 14 { 15 static string ServiceName = ConfigurationManager.AppSettings["ServiceName"]; 16 /// <summary> 17 /// 應用程序的主入口點。 18 /// </summary> 19 static void Main(string[] args) 20 { 21 //帶參啓動運行服務 22 if (args.Length > 0) 23 try 24 { 25 ServiceBase[] serviceToRun = new ServiceBase[] { new ServiceInit() }; 26 ServiceBase.Run(serviceToRun); 27 } 28 catch (Exception ex) 29 { 30 LogHelper.Error("服務異常:\r\n" + ex.Message + "\r\n" + ex.InnerException); 31 } 32 33 34 //不帶參啓動配置程序 35 else 36 { 37 ServiceInstallWindow(); 38 } 39 40 Console.ReadKey(); 41 } 42 /// <summary> 43 /// 啓動安裝服務界面 44 /// </summary> 45 static void ServiceInstallWindow() 46 { 47 while (true) 48 { 49 Console.WriteLine("請選擇你要執行的操做:"); 50 Console.WriteLine("1運行服務"); 51 Console.WriteLine("2中止服務"); 52 Console.WriteLine("3安裝服務"); 53 Console.WriteLine("4卸載服務"); 54 Console.WriteLine("5驗證服務狀態"); 55 Console.WriteLine("6退出"); 56 Console.WriteLine("————————————————————"); 57 58 char keyChar = Console.ReadKey().KeyChar; 59 60 //運行服務 61 if (keyChar == '1') 62 { 63 Console.WriteLine("\r\n服務已啓動,請稍後......"); 64 if (ServiceHelper.IsServiceExisted(ServiceName)) 65 { 66 ServiceHelper.StartService(ServiceName); 67 Console.WriteLine("\r\n服務已啓動!"); 68 } 69 else 70 { 71 Console.WriteLine("\r\n服務不存在......"); 72 } 73 } 74 //中止服務 75 if (keyChar == '2') 76 { 77 Console.WriteLine("\r\n服務正在中止,請稍後......"); 78 if (ServiceHelper.IsServiceExisted(ServiceName)) 79 { 80 ServiceHelper.StopService(ServiceName); 81 Console.WriteLine("\r\n服務已中止!"); 82 } 83 else 84 { 85 Console.WriteLine("\r\n服務不存在......"); 86 } 87 } 88 //安裝服務 89 else if (keyChar == '3') 90 { 91 if (!ServiceHelper.IsServiceExisted(ServiceName)) 92 { 93 ServiceHelper.ConfigService(ServiceName, true); 94 } 95 else 96 { 97 Console.WriteLine("\r\n服務已存在......"); 98 } 99 } 100 //卸載服務 101 else if (keyChar == '4') 102 { 103 if (ServiceHelper.IsServiceExisted(ServiceName)) 104 { 105 ServiceHelper.ConfigService(ServiceName, false); 106 } 107 else 108 { 109 Console.WriteLine("\r\n服務不存在......"); 110 } 111 } 112 //驗證服務 113 else if (keyChar == '5') 114 { 115 if (!ServiceHelper.IsServiceExisted(ServiceName)) 116 { 117 Console.WriteLine("\r\n服務不存在......"); 118 } 119 else 120 { 121 Console.WriteLine("\r\n服務狀態:" + ServiceHelper.GetServiceStatus(ServiceName).ToString()); 122 } 123 } 124 //退出 125 else if (keyChar == '6') 126 { 127 break; 128 } 129 else 130 { 131 Console.WriteLine("\r\n請輸入一個有效鍵!"); 132 Console.WriteLine("————————————————————"); 133 } 134 } 135 } 136 } 137 }
ServiceHelper 代碼:
using System; using System.Threading; using System.Reflection; using System.Collections; using System.ServiceProcess; using System.Configuration.Install; namespace RabbitMQClientService.Common { public class ServiceHelper { #region 服務是否存在 /// <summary> /// 服務是否存在 /// </summary> /// <param name="serviceName">服務名</param> /// <returns></returns> public static bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == serviceName) { return true; } } return false; } #endregion #region 啓動服務 /// <summary> /// 啓動服務 /// </summary> /// <param name="serviceName">服務名</param> public static void StartService(string serviceName) { using (ServiceController service = new ServiceController(serviceName)) { //判斷服務狀態 if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending) { try { service.Start(); //啓動服務 for (int i = 0; i < 60; i++) { service.Refresh(); Thread.Sleep(1000); if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running) //判斷服務是否正常運行 { break; } if (i == 59) { LogHelper.WriteErrorLog("啓動服務失敗:" + serviceName, null); } } } catch (Exception ex) { LogHelper.WriteErrorLog("啓動服務失敗:" + ex.Message, ex); } } } } #endregion #region 中止服務 /// <summary> /// 中止服務 /// </summary> /// <param name="serviceName">服務名</param> public static void StopService(string serviceName) { using (ServiceController service = new ServiceController(serviceName)) { //判斷服務狀態 if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running) { try { if (service.CanStop) { // 若是權限不夠是不能Stop()的。 service.Stop(); // 這句話若是沒有對該服務的後續操做能夠不要,C#程序只是以權限向操做系統發出關閉某服務的消息而已,真正關閉該服務的是操做系統而非此C#程序(下面的Start的也同樣) service.WaitForStatus(ServiceControllerStatus.Stopped); } } catch (Exception ex) { LogHelper.WriteErrorLog("中止服務失敗: \r\n" + ex.Message, ex); } } } } #endregion #region 獲取服務狀態 /// <summary> /// 獲取服務狀態 /// </summary> /// <param name="serviceName">服務名</param> /// <returns></returns> public static ServiceControllerStatus GetServiceStatus(string serviceName) { ServiceController service = new ServiceController(serviceName); return service.Status; } #endregion #region 配置服務(安裝和卸載) /// <summary> /// 配置服務(安裝和卸載) /// </summary> /// <param name="serviceName">服務名</param> /// <param name="install">是否安裝,true安裝,false 卸載</param> public static void ConfigService(string serviceName, bool install) { TransactedInstaller ti = new TransactedInstaller(); ti.Installers.Add(new ServiceProcessInstaller { Account = ServiceAccount.LocalSystem }); ti.Installers.Add(new ServiceInstaller { DisplayName = serviceName, ServiceName = serviceName, Description = "考勤數據同步", StartType = ServiceStartMode.Automatic//運行方式 }); ti.Context = new InstallContext(); ti.Context.Parameters["assemblypath"] = "\"" + Assembly.GetEntryAssembly().Location + "\" /service"; if (install) //是否安裝服務 { ti.Install(new Hashtable()); } else { ti.Uninstall(null); } } #endregion } }
該方法主要引用了 System.ServiceProcess.ServiceController 類,code
界面效果以下:blog