C# windows服务:
第一种 :通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)
步骤:
1。运行--〉cmd:打开cmd命令框
2。在命令行里定位到InstallUtil.exe所在的位置
InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft.NET/Framework/v2.0.50727里面,所以你要在cmd里通过cd定位到该位置(cd C:/Windows/Microsoft.NET/Framework/v2.0.50727)
3。操作命令:
1). 安装服务命令:在命令行里输入下面的命令:
InstallUtil.exe Path/WinServiceName.exe
其中Path表示ServiceName.exe所在的位置,回车即可
2). 启动服务命令
net start ServiceName
ServiceName是真正的Service的名称(ServiceBase.ServiceName),跟.exe的名称可能一样,也可能不一样。如果不清楚,就到已安装的服务里面找到你的服务,右键属性里面看服务名称
3). 停止服务命令
net stop ServiceName
4). 卸载服务命令:在命令行里输入下面的命令:
InstallUtil.exe /u Path/WinServiceName.exe
其中Path表示ServiceName.exe所在的位置,回车即可
使用VS调用InstallUtil.exe工具,输入参数:
安装:D:\GCAMS\Code\PublicClass\SaveLogWindowsService\bin\Debug\SaveLogWindowsService.exe启动:cmd--》net start ServiceName或者打开服务管理界面,选择需要启动的服务,右击启动服务
卸载:/U D:\GCAMS\Code\PublicClass\SaveLogWindowsService\bin\Debug\SaveLogWindowsService.exe
创建安装bat文件
安装Socket服务(Server).bat
@echo on color 2f mode con: cols=80 lines=25echo 请按任意键开始安装SocketServer后台服务...pauseC:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe SocketWindowsService.exerem net start SocketServersc start SocketServer %1pause
创建安装bat文件
卸载Socket服务(Server).bat
@echo on color 2f mode con: cols=80 lines=25echo 请按任意键开始卸载SocketServer后台服务...pauseC:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u SocketWindowsService.exepause
第二种:使用WindowsServiceHelper类进行安装
using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceProcess;using System.Collections;using Microsoft.Win32;using System.Configuration.Install;namespace OperationWinService{ public static class WindowsServiceHelper { #region 已封装Window服务 private static string ServerName = ConfigurationManager.AppSettings["WinServiceName"].ToString(); private static string ExecuteName = ConfigurationManager.AppSettings["ExecuteName"].ToString(); ////// 安装服务 /// /// Windows服务显示名称 ///存在返回 true,否则返回 false; public static bool InstallService() { bool flag = false; if (!IsServiceIsExisted()) { try { string location = System.Reflection.Assembly.GetExecutingAssembly().Location; string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + ExecuteName + ".exe"; //测试用的绝对路径 //string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe"; InstallMyService(null, serviceFileName); flag = true; } catch(Exception ex) { flag = false; LogHelper.WriteLog(typeof(WindowsServiceHelper), "InstallService执行错误:" + ex.Message); } } else { flag = true; LogHelper.WriteLog(typeof(WindowsServiceHelper), "InstallService执行配置服务名称不存在"); } return flag; } ////// 卸载服务 /// /// Windows服务显示名称 ///存在返回 true,否则返回 false; public static bool UninstallService() { bool flag = false; if (IsServiceIsExisted()) { try { string location = System.Reflection.Assembly.GetExecutingAssembly().Location; string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + ExecuteName + ".exe"; //测试用的绝对路径 //string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe"; UnInstallMyService(serviceFileName); flag = true; } catch (Exception ex) { flag = false; LogHelper.WriteLog(typeof(WindowsServiceHelper), "UninstallService执行错误:" + ex.Message); } } else { flag = true; LogHelper.WriteLog(typeof(WindowsServiceHelper), "UninstallService执行配置服务名称不存在"); } return flag; } ////// 检查Windows服务是否存在 /// /// Windows服务显示名称 ///存在返回 true,否则返回 false; public static bool IsServiceIsExisted() { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName.ToLower() == ServerName.ToLower()) { return true; } } return false; } ////// 安装Windows服务 /// /// 集合 /// Windows服务程序文件路径 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(); } ////// 卸载Windows服务 /// /// Windows服务程序文件路径 private static void UnInstallMyService(string filePath) { AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller(); AssemblyInstaller1.UseNewContext = true; AssemblyInstaller1.Path = filePath; AssemblyInstaller1.Uninstall(null); AssemblyInstaller1.Dispose(); } ////// 判断某个Windows服务是否启动 /// /// Windows服务显示名称 ///bool public static bool IsServiceStart() { bool bStartStatus = false; ServiceController psc = new ServiceController(ServerName); try { if (!psc.Status.Equals(ServiceControllerStatus.Stopped)) { bStartStatus = true; } return bStartStatus; } catch (Exception ex) { throw new Exception(ex.Message); } } ////// 修改服务的启动项 2为自动,3为手动 /// /// 2为自动,3为手动 /// Windows服务显示名称 ///bool 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; } ////// 启动服务 /// /// Windows服务显示名称 ///bool public static bool StartService() { bool flag = true; try { if (IsServiceIsExisted()) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServerName); 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; } } } } else { flag = false; } } catch(Exception ex) { LogHelper.WriteLog(typeof(WindowsServiceHelper), "StartService执行错误:" + ex.Message); } return flag; } ////// 停止服务 /// /// Windows服务显示名称 ///bool public static bool StopService() { bool flag = true; try { if (IsServiceIsExisted()) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServerName); 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; } } } } else { flag = false; } } catch(Exception ex) { LogHelper.WriteLog(typeof(WindowsServiceHelper), "StopService执行错误:" + ex.Message); } return flag; } #endregion }}