zoukankan      html  css  js  c++  java
  • 创建C# Windows服务程序


    一、创建服务程序

    第一步、创建Windows服务(.NET Framework)

    第二步、进入Service1()

    第三步、编写在开启服务和停止服务时的事务

    using System;
    using System.IO;
    using System.ServiceProcess;
    
    namespace Demasiah_Services
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
                using(FileStream fs = new FileStream(@"d:windowsServicesTest.txt", 
                    FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using(StreamWriter sw=new StreamWriter(fs))
                    {
                        sw.BaseStream.Seek(0, SeekOrigin.End);
                        sw.WriteLine($"WidowsServices:Service Started {DateTime.Now} ;
    ");
                        sw.Flush();
                    }
                }
            }
    
            protected override void OnStop()
            {
                using (FileStream fs = new FileStream(@"d:windowsServicesTest.txt", 
                    FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.BaseStream.Seek(0, SeekOrigin.End);
                        sw.WriteLine($"WidowsServices:Service Stoped {DateTime.Now} ;
    ");
                        sw.Flush();
                    }
                }
            }
        }
    }
    
    

    第四步、直接在service设计视图上右键添加安装程序

    第五步、

    第六步、StartType:自动启动;serivcename即在window服务窗口显示的名称

    第七步、右键服务程序项目 -> 生成。

    二、安装服务

    第一步、右键cmd以管理员身份运行;
    第二步、输入 cd C:WindowsMicrosoft.NETFrameworkv4.0.30319 回车
    第三步、
    安装Windows服务:输入 InstallUtil.exe D:xuxuzhaozhaoServicesinDebugWinServiceTest.exe 回车;
    删除Windows服务:sc delete WinServiceTest(SerivceName)

  • 相关阅读:
    AtCoder Grand Contest 033
    Luogu P6620 [省选联考 2020 A 卷] 组合数问题
    Luogu P6631 [ZJOI2020] 序列
    Luogu P6630 [ZJOI2020] 传统艺能
    Luogu P6633 [ZJOI2020] 抽卡
    Luogu P6623 [省选联考 2020 A 卷] 树
    AtCoder Grand Contest 034
    Luogu P5445 [APIO2019] 路灯
    LOJ #6059. 「2017 山东一轮集训 Day1」Sum
    Luogu P3721 [AH2017/HNOI2017]单旋
  • 原文地址:https://www.cnblogs.com/xuxuzhaozhao/p/7390809.html
Copyright © 2011-2022 走看看