C#创建Windows service并安装运行
一、创建Windows serveice
1.1 创建项目
点击"新建"
1.2 项目重命名
将Service1重命名为你服务名称,这里我们命名为ServiceTest。
二、编写service代码
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.IO;
using System.Threading;
namespace TestService1
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer1;//计时器
public Service1()
{
InitializeComponent();
}
//启动服务时执行
protected override void OnStart(string[] args)
{
timer1 = new System.Timers.Timer();
timer1.Interval = 60000;//执行时间间隔60s
timer1.Elapsed += new System.Timers.ElapsedEventHandler(TestWrite);
timer1.Enabled = true;
}
//具体执行的方法程序
private void TestWrite(object sender, System.Timers.ElapsedEventArgs e)
{
while (true)
{
string FILE_NAME = "D:/servicelog.txt";
StreamWriter sr;
if (File.Exists(FILE_NAME)) //如果文件存在,则创建File.AppendText对象
{
sr = File.AppendText(FILE_NAME);
}
else //如果文件不存在,则创建File.CreateText对象
{
sr = File.CreateText(FILE_NAME);
}
string content = "这只是个测试" + System.DateTime.Now.ToString();
sr.WriteLine(content);//将传入的字符串加上时间写入文本文件一行
sr.Close();
}
}
//停止服务时执行
protected override void OnStop()
{
this.timer1.Enabled=false;
}
}
}
三、创建服务安装程序
3.1 添加安装程序
右键选择"添加安装程序"
3.2 修改安装服务名
右键serviceInsraller1,选择属性,将ServiceName的值改为ServiceTest,启动方式为手动。
3.3 修改安装权限
右键serviceProcessInsraller1,选择属性,将Account的值改为LocalSystem。
3.4 生成项目
右键点击项目,进行Windows service的编译生成
3.5 创建安装脚本
在项目中添加2个文件如下(必须是ANSI或者UTF-8无BOM格式):
1)安装脚本Install.bat
# %SystemRoot%一般为C:\Windows
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe C:\Users\User\source\repos\WindowsServicetest\bin\Debug\WindowsServicetest.exe
# 启动服务
Net Start cstor_iscsi_agent_service
# 设置服务自动运行,也可在安装程序中设置
sc config cstor_iscsi_agent_service start=auto
# 查看脚本运行情况
pause
2) 卸载脚本Uninstall.bat
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /u C:\Users\User\source\repos\WindowsServicetest\bin\Debug\WindowsServicetest.exe
pause
以上脚本以管理员权限执行即可。
四、调试
Windows service不可以直接F5运行。执行以下步骤
1)安装并运行服务
2)附加进程,在代码中打上断点即可开始调试
五、安装与启动Windows service
(一)如何安装服务:
1、 C:\Windows\Microsoft.NET\Framework\我们要启动frameword.net的版本
2、 Win+R——》cd C:\Windows\Microsoft.NET\Framework\我们要启动frameword.net的版本
3、 installUtil 服务.exe所在路径
(二)如何启动服务
Win+R——》services.msc,选中自己需要启动的服务,右击,启动
(三)如何卸载服务
1、 关闭正在调试的服务程序
2、 重复安装服务的前两个步骤
3、 installUtil /u 服务.exe所在路径