使用的是VS2015 + .NET Framework 4.5
1.用vs创建一个Windows 服务
打开vs,在左上角菜单栏中选择 文件->新建->项目
2.创建之后项目结构如下
主要是针对service1.cs这个文件
Service1中是windows服务的逻辑代码,这里我们执行一个写入的操作,将当前时间写入到txt,
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;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
/// <summary>
/// 服务启动时执行这个方法
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
//执行写入txt操作 路径可以填你自己的想要放txt的路径,
FileStream fs = new FileStream(@"D:\service.txt",FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("now date:"+DateTime.Now);
sw.WriteLine("hello world");
sw.Flush();
sw.Close();
fs.Close();
}
/// <summary>
/// 服务停止时执行此方法
/// </summary>
protected override void OnStop()
{
}
}
}
3.在代码写好后,需要设置安装服务,
打开Service1.cs,打开后右键,会出现选项,选择添加安装程序
点击之后会添加一下两个东西,其中serviceInstaller1就是服务的安装程序,我们需要对其属性进行设置
配置服务的属性
然后配置serviceProcessinstall1
右键项目,点击生成
4.安装服务
安装服务工具在framework下,在控制台中切换到你自己的framework目录下,比如说我的安装目录在C:\Windows\Microsoft.NET\Framework64\v4.0.30319
命令为:cd 你的安装目录
启动安装服务工具
C:\Users\user\Documents\Visual Studio 2015\Projects\WindowsService1\WindowsService1\bin\Debug
项目路径:
命令为:installutil.exe 项目路径
成功之后 在服务里面去找你的服务
win+r键 ,搜索框输入 services.msc ,进入服务
找到你刚才设置的实例名,启动服务,启动成功后到D盘看是否生成对应文本
成功生成txt
卸载服务
命令:installutil.exe /u 项目路径
已成功卸载