使用.Net Core 2.2创建windows服务我的环境win 10 homeVisual Studio 2019 v16.1.3安装有.net core 2.2创建项目编辑项目文件在 PropertyGroup 配置节 加入属性 RuntimeIdentifierwin-x64/RuntimeIdentifier保...

使用.Net Core 2.2创建windows服务
我的环境
- win 10 home
- Visual Studio 2019 v16.1.3
- 安装有.net core 2.2
创建项目
编辑项目文件
在 PropertyGroup 配置节 加入属性 <RuntimeIdentifier>win-x64</RuntimeIdentifier>
保存后,重新生成项目
在项目文件夹下,会有文件夹 bin\Debug\netcoreapp2.2\win-x64,里面包含了exe文件。
测试服务类的编写
安装nuget包
Install-Package System.ServiceProcess.ServiceController -Version 4.5.0
修改启动类 Programe.cs
using System;
using System.IO;
using System.ServiceProcess;
namespace TestService
{
class Program
{
static void Main(string[] args)
{
using (var service = new TestSevice())
{
ServiceBase.Run(service);
}
}
}
internal class TestSevice : ServiceBase
{
public TestSevice()
{
ServiceName = "TestService";
}
protected override void OnStart(string[] args)
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
}
protected override void OnStop()
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
}
private static string CheckFileExists()
{
string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"\MyService.txt";
if (!File.Exists(filename))
{
File.Create(filename);
}
return filename;
}
}
}
服务安装、启动、卸载
安装
sc create testservice binpath=D:\source\repos\TestConsoleService\TestService\bin\Debug\netcoreapp2.2\win-x64\TestService.exe
卸载
sc delete testservice
启动
不能通过命令行启动服务
sc start testservice
只能去服务管理器使用鼠标启动服务,具体原因暂未研究
反复启动停止,然后去exe所在目录下查看MyService.txt的内容,确认服务的启动。
参考文档
- Running a .NET Core Generic Host App as a Windows Service
- Create windows service using .Net Core (Console application)
本文标题为:使用.Net Core 2.2创建windows服务


基础教程推荐
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- 实例详解C#实现http不同方法的请求 2022-12-26