C# 将应用程序注册成服务

写在前面

有时候我们需要将程序以Windows服务的模式运行,以下是一种非常简单的实现方式。

实现步骤

1.新建一个控制台项目

2.添加App.config,指定服务名称

<configuration>
    <appSettings>
        <add key="ServiceName" value="MyService" />
    </appSettings>
</configuration>

 3.主要实现代码

    public class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                var serviceName = ConfigurationManager.AppSettings["ServiceName"];
                if (string.IsNullOrEmpty(serviceName))
                {
                    string err = "service name is null";
                    Console.WriteLine(err);
                    return;
                }

                if (args.Count() < 1)
                {
                    Console.WriteLine("Setup Ok");
                    Console.WriteLine("Start Ok");
                }
                else if (args.Count() > 0 && args.First() == "--service")
                {
                    ServiceBase.Run(new MyService());
                }
                else if (args.Count() > 0 && args.First() == "--reg")
                {
                    //by calling the SC program of windows, Administration permission needed.
                    var arg = string.Format(" create {0} displayname= \"{0}\" binpath= \""
                                            + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Assembly.GetEntryAssembly().GetName().Name + ".exe")
                                            + " --service\"",
                                            serviceName);
                    var ps = new ProcessStartInfo("sc.exe", arg);
                    ps.WindowStyle = ProcessWindowStyle.Hidden;
                    ps.UseShellExecute = false;
                    var p = Process.Start(ps);
                    p.WaitForExit();

                }//Remove this self from windows services.
                else if (args.Count() > 0 && args.First() == "--unreg")
                {
                    var ps = new ProcessStartInfo("sc.exe", string.Format(" delete {0}", serviceName));
                    ps.WindowStyle = ProcessWindowStyle.Hidden;
                    ps.UseShellExecute = false;
                    var p = Process.Start(ps);
                    p.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine("Exception:" + e.ExceptionObject.ToString());
        }
    }
    class MyService : ServiceBase
    {
        public MyService()
        {
            // 构造器
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                // 调用服务启动时需要执行的方法
                base.OnStart(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected override void OnStop()
        {
            try
            {
                // 调用服务停止时需要执行的方法
                base.OnStop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected override void OnPause()
        {
            try
            {
                // 调用服务暂停时需要执行的方法
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected override void OnContinue()
        {
            try
            {
                // 调用服务恢复时需要执行的方法
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

验证结果

使用cmd执行,或者做一个批处理;执行RegServiceTest.exe --reg

运行 services.msc 可以查看到服务已经成功创建了。

  • 17
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值