C# 写一个简单的Windows Service的服务程序

项目创建及设定部分

使用VS2019创建项目,选择C# Service的选项

按照你喜欢的方式命名,我这边就默认了

添加安装服务,在Service1.cs[Design]中

在设计界面右击,选择如下的"Add Installer"

在出现的"ProjectInstaller.cs[Design]"中的serviceProcessInstaller1属性中的Account中选择"LocalSystem"

在出现的"ProjectInstaller.cs[Design]"中的serviceInstall1属性中的ServiceName中设定你想要的名字,例如我设定的名字叫Tody;那在微软的服务系统中,名字就叫Tody;

代码编写部分

右击Service1.cs,选择"View Code"的选项,或直接按F7按钮进入代码部分

如下为Service1的类,这是我们可以在OnStart和OnStop的函数中增加我们的代码;

详细代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {

        private readonly Timer TodyTimer;

        internal void TodyTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                using (FileStream fileStream = new FileStream(@"E:\Tody.log", FileMode.Append))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fileStream))
                    {
                        streamWriter.WriteLine("{0} - {1} ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Tody Test");
                    }
                }
            }
            catch (Exception ex)
            {
               //ex.Message;
            }
        }

        public Service1()
        {
            InitializeComponent();

            // Initial Timer 
            TodyTimer = new Timer(1500); //1.5s
            TodyTimer.Elapsed += TodyTimer_Elapsed;

        }

        protected override void OnStart(string[] args)
        {
            TodyTimer.Start();
        }

        protected override void OnStop()
        {
            TodyTimer.Stop();
        }
    }
}
安装服务部分

在VS2019的命令行中运行安装程序:InstallUtil.exe,该程序在"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"中

在编译的目录下运行指令:installutil WindowsService1.exe 进行服务的安装(++记得要用管理员++)

如果要卸载 服务的话installutil /u WindowsService1.exe

如下安装成功的结果

启动或停止服务

在系统服务中找到Tody的服务,如下图,右击启动

启动后在E盘的根目录产生了一个文件,就是代码中定义的;

文件中的结果

停止服务则直接选择停止就可以了;

这样,一个简单的服务程序就这样搞定了;应该不难吧;

相关推荐
曦夜日长6 分钟前
C++ STL容器string(一):string的变量细节、默认函数的认识以及常用接口的使用
java·开发语言·c++
代码中介商8 分钟前
C++ STL 标准模板库完全指南:从容器到迭代器
开发语言·c++·stl
winner888111 分钟前
C++ 构造函数、析构函数、虚函数、虚析构
开发语言·c++
北山有鸟13 分钟前
IS_ERR 判断出错后,再用 PTR_ERR 把它强制转换回 int 型的错误码作为函数的返回值。
java·开发语言
格林威17 分钟前
工业视觉检测:提供可视化UI调试工具的实现方式是什么?
开发语言·人工智能·数码相机·ui·计算机视觉·视觉检测·工业相机
phltxy19 分钟前
深度解析:Spring Cloud Gateway 从入门到实战
java·开发语言
AI进化营-智能译站28 分钟前
ROS2 C++开发系列08-传感器数据缓存与指令解析方式之数组、向量与字符串实战
开发语言·c++·缓存·ai
shjita34 分钟前
记录java执行中的一个错误细节
java·开发语言
AI进化营-智能译站40 分钟前
ROS2 C++开发系列14-Lambda表达式处理传感器数据流|文件IO保存机器人实验日志
开发语言·c++·ai·机器人
itzixiao1 小时前
L1-067 洛希极限(10分)[java][python]
java·开发语言·算法