VS2022创建Windows服务程序的方法步骤
目录
- 创建一个Windows服务程序
- 可以创建Windows服务程序
- 配置相关信息
- 脚本可执行文件
- 执行脚本文件
- 如果不能创建Windows服务程序
- 简单地使用
- 创建一个新的Windows服务
- 其他的问题
- 更改代码后需要重新生成
- 某些命名空间如无效需手动引入
- 脚本问题
创建一个Windows服务程序
可以创建Windows服务程序
打开VS2022,新建项目。


创建成功后的目录结构如左侧所示,至此项目构建完成。

配置相关信息
添加安装程序



重新生成一下解决方案

至此配置完成。
脚本可执行文件
在工程目录的bin\Debug目录下 新建两个脚本文件–install.bat和uninstall.bat,分别用于安装服务和卸载服务。

install.bat
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe %~dp0MyFirstWindowsService.exe Net Start MyFirstService sc config MyFirstService start=auto pause
简单说明

uninstall.bat
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /u %~dp0MyFirstWindowsService.exe pause
至此配置完成。
执行脚本文件
执行安装脚本文件

可以右键我的电脑 -> 管理 找到服务,在右侧寻找我们自己的服务名称


执行卸载脚本文件

如果不能创建Windows服务程序
如果输入上述条件没有找到可创建的工程,点击安装多个工具和功能。

或者在某个工程的工具里点击获取工具和功能


等待安装完毕,按上面的步骤来即可。
简单地使用
使用本机服务和定时器Timer,简单做一个WindowsService的记录日志。
创建一个新的Windows服务
按照上述步骤创建一个新的Windows服务,名为WindowsService2,并且服务名称为WindowsService2。
我们主要的代码在Service1.cs中写,选中该文件,右键选择查看代码。

记得在App.config中设置键值对 value是日志记录地址 可自行选择。

主要代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.IO;
using System.Configuration;
namespace WindowsService2
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        //创建定时器
        public System.Timers.Timer ServiceTimer;
        //从App.config中取值 这里我的日志文件位置在F:\log.txt 这里可以自行设置
        public string filePath = ConfigurationManager.AppSettings["FilePath"];
        //主要功能代码在这里写
        protected override void OnStart(string[] args)
        {
            //日志记录方法
            WriteLog(filePath, "启动服务。");
            InitTimer();//初始化的定时器
        }
        protected override void OnStop()
        {
            //停止服务
            WriteLog(filePath , "停止服务。");
        }
        public void InitTimer()
        {
            //设置定时器两秒执行一次
            ServiceTimer = new System.Timers.Timer(2000);
            //执行的操作为Excute
            ServiceTimer.Elapsed += Excute;
            //是否重复执行
            ServiceTimer.AutoReset = true;
            //是否执行Elapsed中的事件
            ServiceTimer.Enabled = true;
        }
        public void Excute(Object o , System.Timers.ElapsedEventArgs e)
        {
            //判断是否执行
            if (!File.Exists(filePath))
            {
                //不存再则创建
                File.Create(filePath);
            }
            //再这里写入日志
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            WriteLog(filePath, DateTime.Now.ToString(), "进行了操作。 日志文件路径位于: " + filePath + " AppSetting : " + ConfigurationManager.AppSettings["FilePath"]);
        }
        //写入日志文件
        public static void WriteLog(string path, params string[] s)
        {
            //创建输入流
            System.IO.StreamWriter writer = null;
            try
            {
                writer = new System.IO.StreamWriter(path, true);
                StringBuilder sb = new StringBuilder("");
                for (int i = 0; i < s.Length; i++)
                {
                    sb.Append(" ");
                    sb.Append(s[i]);
                }
                writer.WriteLine(sb.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //关闭流 释放资源
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }
        }
    }
}
执行结果

其他的问题
更改代码后需要重新生成
每次更改执行代码后需要右键项目 -> 重新生成,否则更改不会生效。

某些命名空间如无效需手动引入
以Configuration的命名空间举例,即使加了using System.Configuration; 也有可能出现ConfigurationManager无法使用,这时我们可以手动引入。
找到工程右侧引入,右键添加引用。



脚本问题
编码问题
创建bat文件时,有时候字符集编码可能不对,导致脚本执行时出现问题,我们可以用Notepad3打开,更改编码格式为ANSI或者UTF-8。

权限问题
执行脚本文件时,需要右键以管理员身份运行,否则就会出现以下情况,导致服务安装失败。

空格问题
如果脚本某些地方出现空格,会导致脚本运行失败。
比如
会导致以下报错

到此这篇关于VS2022创建Windows服务程序的方法步骤的文章就介绍到这了,更多相关VS2022创建Windows服务程序内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

