创建C# Windows服务程序

it2024-08-08  67


一、创建服务程序

第一步、创建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} ;\n"); 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} ;\n"); sw.Flush(); } } } } }

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

第五步、

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

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

二、安装服务

第一步、右键cmd以管理员身份运行; 第二步、输入 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 回车 第三步、 安装Windows服务:输入 InstallUtil.exe D:\xuxuzhaozhao\Services\bin\Debug\WinServiceTest.exe 回车; 删除Windows服务:sc delete WinServiceTest(SerivceName)

转载于:https://www.cnblogs.com/xuxuzhaozhao/p/7390809.html

最新回复(0)