首页 > 系统相关 >C# 注册Windows服务

C# 注册Windows服务

时间:2024-11-19 17:17:52浏览次数:1  
标签:ServiceHelper Console 注册 C# Windows ServiceName key serviceName ConsoleKey

环境:.NET Farmework 4.7.2

IDE:Visual Studio 2022

添加程序集引用:

System.ServiceProcess

System.Configuration.Install

右键项目,添加UpdateServices1类,让UpdateServices1继承ServiceBase(UpdateServices1换成自己的Services服务)

 

编译过后如果需要更新服务代码,要在Windows服务里面先停止

const string ServiceName = "ClientUpdateServices";
        const string ServiceDescription = "服务描述";
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                try
                {
                    ServiceBase[] serviceToRun = new ServiceBase[] { new UpdateServices1() };
                    ServiceBase.Run(serviceToRun);
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
            StartLable:
                Console.WriteLine("请选择你要执行的操作——1:自动部署服务(Q),2:安装服务(W),3:卸载服务(E),4:验证服务状态(R),5:退出(T)");
                Console.WriteLine("————————————————————");
                ConsoleKey key = Console.ReadKey().Key;
                string conkey = Console.ReadLine();
                ServiceHelper.SetServicesDesc(ServiceDescription);
                if (key == ConsoleKey.NumPad1 || key == ConsoleKey.D1 || key == ConsoleKey.Q || conkey == "1")
                {
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, false);
                    }
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, true);
                    }
                    ServiceHelper.StartService(ServiceName);
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad2 || key == ConsoleKey.D2 || key == ConsoleKey.W || conkey == "2")
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, true);
                    }
                    else
                    {
                        Console.WriteLine("\n服务已存在......");
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad3 || key == ConsoleKey.D3 || key == ConsoleKey.E || conkey == "3")
                {
                    if (ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        ServiceHelper.ConfigService(ServiceName, false);
                    }
                    else
                    {
                        Console.WriteLine("\n服务不存在......");
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad4 || key == ConsoleKey.D4 || key == ConsoleKey.R || conkey == "4")
                {
                    if (!ServiceHelper.IsServiceExisted(ServiceName))
                    {
                        Console.WriteLine("\n服务不存在......");
                    }
                    else
                    {
                        Console.WriteLine("\n服务状态:" + ServiceHelper.GetServiceStatus(ServiceName).ToString());
                    }
                    goto StartLable;
                }
                else if (key == ConsoleKey.NumPad5 || key == ConsoleKey.D5 || key == ConsoleKey.T || conkey == "5") { }
                else
                {
                    Console.WriteLine("\n请输入一个有效键!");
                    Console.WriteLine("————————————————————");
                    goto StartLable;
                }
            }
        }
Program

 

public static class ServiceHelper
    {
        static string ServiceDescription = "";

        public static void SetServicesDesc(string serviceDesc)
        {
            ServiceDescription = serviceDesc;
        }

        /// <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;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StartService(string serviceName)
        {
            if (IsServiceExisted(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)
                        {
                            throw new Exception("Start Service Error:" + serviceName);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取服务状态
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
            return service.Status;
        }

        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="install"></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 = ServiceDescription,
                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);
            }
        }
    }
ServiceHelper

 

标签:ServiceHelper,Console,注册,C#,Windows,ServiceName,key,serviceName,ConsoleKey
From: https://www.cnblogs.com/kjgagaga/p/18555236

相关文章

  • 无人机垂起复合翼基础介绍——CKESC电调小课堂13
    无人机垂起复合翼是一种融合了垂直起降(VTOL)能力和固定翼飞行优势的无人机类型。CKESC-专业级电调研发生产供应商一、结构特点1.机翼设计   它有固定机翼,机翼形状和尺寸根据无人机的具体用途(如长航时侦察、物流运输等)设计。机翼通常采用轻质高强度的材料,如碳纤维等,以减......
  • 【C++】十六进制数据的字节序排列问题、大小端
    十六进制数据的字节序排列问题,涉及到大小端(Endianness)的概念。包括它与大小端存储方式的关系。1.十六进制数据在内存中的存储定义的数据#defineFRAME_TYPE_PARAM_SET0x30010x3001是一个16位(2字节)整数。在内存中,0x3001的存储方式依赖于系统的字节序:小端......
  • WasomCodeX试用-工程文件结构
    官方的Gitee提供了Tutorial程序供下载学习。打开后,可以看到程序结构。在这个程序里,可以看到从main主程序到各个FC都写在一个文件里。同时,通过终端查看下文件目录结构。/wasomeide_workspace/tutorials/projects/ch05-1$tree-l.├──ams_pack.log├──build│├......
  • cloud run job with override
    Ifyou'reworkingwithGoogleCloudRunandneedtooverridejobsettingsprogrammaticallyusingtheJavaAPI,youcanusetheGoogleCloudClientLibrariesforJava.TheselibrariesprovideawaytointeractwithGoogleCloudservices,includingClo......
  • AtCoder Beginner Contest 352 - VP记录
    A-AtCoderLine赛时整活想写异或版本的swap写错了还WA了一发。不过现在会写了:x^=y^=x^=y点击查看代码#include<cstdio>#include<algorithm>usingnamespacestd;intmain(){ intn,x,y,z; scanf("%d%d%d%d",&n,&x,&y,&z); if(x>y)swap(x,y); p......
  • CSS在Table列右上角添加标记简单实现
    实现效果代码<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>TableRibbonDemo</......
  • 【搬运】Linux Command Syntax – Arguments & Options Explained
    本文摘自:https://thenerd.academy/linux-command-syntax-arguments-options-explained/ ThislessonisallabouttheLinuxcommandsyntax!We’regoingtoexplorehowtocustomizethebehaviorofourcommandsbyusingargumentsandoptions.So,fastenyour......
  • 【刷题笔记】[BalticOI 2024] Portal
    【刷题笔记】[BalticOI2024]Portal\(Solution\)先注意到,题目中的图形是许多的自相似图形,要求能满足要求的单位图形的最大面积先考虑只有一维的情况,设几个传送门的坐标为\((a_i,0)\)```发现将整个图形平移后答案不会改变,所以不妨把一个传送门移动到\((0,0)\)可以发现单......
  • 安利一款好用的 gRPC 调试工具 Apifox
    各位用gRPC的小伙伴们!今天要给大家安利一个超好用的gRPC调试神器-Apifox!它对gRPC的支持真的是太友好了,让我们一起来看看~gRPC调试功能有多强?支持的调用类型描述使用场景一元调用类似HTTP请求的简单调用常规的请求-响应场景服务端流服务器端持续推送数据实时......
  • json解析之fastjson和jackson使用对比
    json解析之fastjson和jackson使用对比前言最近项目中需要做埋点分析,首先就需要对埋点日志进行解析处理,刚好这时候体验对比了下fastjson和jackson两者使用的区别,以下分别是针对同一个json串处理,最终的效果都是将json数据解析出来,并统一展示。一、fastjson简介?fastjson是由......