标签:Core string windows win System filename TestService 2.2 using
使用.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)
标签:Core,string,windows,win,System,filename,TestService,2.2,using 来源: https://www.cnblogs.com/xyfy/p/11024597.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。