windows服务控制类
/// <summary> /// 服务调用控制 /// </summary> public class WinServiceController { /// <summary> /// 服务开始启用 /// </summary> /// <typeparam name="T">服务调用的类型</typeparam> /// <param name="ServiceName">服务的名称</param> /// <param name="args">应用程序启动传入的参数</param> public static void State<T>(string ServiceName, string[] args) where T : ServiceBase, IServiceController, new() { string key0 = AppDomain.CurrentDomain.FriendlyName; if (args.Length > 0) { string str = args[0].ToLower(); try { if (str == "-install" || str == "-i") { #region //安装本服务 if (null == ServiceIsExisted(ServiceName)) {//如果没有安装,则安装 string key = AppDomain.CurrentDomain.BaseDirectory + key0; ManagedInstallerClass.InstallHelper(new string[] { key }); ServiceController c = new ServiceController(key0.Substring(0, key0.Length - 4)); c.Start(); } else { Log.Write("服务已经安装!无需再安装!"); } #endregion } else if (str == "-uninstall" || str == "-u") { #region //卸载本服务 ServiceController sc = ServiceIsExisted(ServiceName); if (null != sc) {//如果已经安装,则卸载本服务 if (sc.Status != ServiceControllerStatus.Stopped) { sc.Stop();//停止服务 sc.WaitForStatus(ServiceControllerStatus.Stopped);//等待服务完全停止;真方便的函数~ } string key = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName; ManagedInstallerClass.InstallHelper(new string[] { "/u", key }); } else { Log.Write("服务未安装!不能卸载不存在的服务!"); } #endregion } else if (str == "-start" || str == "-s") { #region //将本服务当做一个应用程序直接运行 Log.Write("消息服务启动开始"); T msm = null; try { msm = new T(); msm.Start(); } catch (Exception msg) { if (null != msm) { msm.Stop(); } } #endregion } } catch (Exception msg) { Log.Write(msg.Message + msg.StackTrace); Log.Write("消息服务异常结束"); } } else { #region //启动本服务 try { ServiceBase.Run(new T()); } catch (Exception msg) { Log.Write(msg.Message + msg.StackTrace); Log.Write("消息服务异常结束"); } #endregion } } /// <summary> /// 检查指定的服务是否存在。 /// </summary> /// <param name="serviceName">要查找的服务名字</param> /// <returns>如果存在则返回真</returns> private static ServiceController ServiceIsExisted(string svcName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == svcName) { return s; } } return null; } }
调用:
在windows服务应用程序中的Program文件
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
WinServiceController.State<Service1>("windows服务应用程序exe名称", args);
}
}
使用工具安装,运行,停止,卸载Window服务
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET