引自:http://www.cnblogs.com/sorex/archive/2012/05/16/2502001.html
一、创建一个Windows Service
1)创建Windows Service项目
2)对Service重命名
将Service1重命名为你服务名称,这里我们命名为ServiceTest。
二、创建服务安装程序
1)添加安装程序
2)修改安装服务名
右键serviceInsraller1,选择属性,将ServiceName的值改为ServiceTest。
3)修改安装权限
右键serviceProcessInsraller1,选择属性,将Account的值改为LocalSystem。
三、写入服务代码
1)打开ServiceTest代码
右键ServiceTest,选择查看代码。
2)写入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; namespace WindowsServiceTest { public partial class ServiceTest : ServiceBase { public ServiceTest() { InitializeComponent(); } protected override void OnStart(string[] args) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\log.txt", true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start."); } } protected override void OnStop() { using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\log.txt", true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop."); } } } }
这里我们的逻辑很简单,启动服务的时候写个日志,关闭的时候再写个日志。
四、创建安装脚本
在项目中添加2个文件如下(必须是ANSI或者UTF-8无BOM格式):
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe %~dp0WindowsServiceTest.exe Net Start ServiceTest sc config ServiceTest start= auto
2)卸载脚本Uninstall.bat
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe /u %~dp0WindowsServiceTest.exe
3)安装脚本说明
第二行为启动服务。
第三行为设置服务为自动运行。
这2行视服务形式自行选择。
4)脚本调试
如果需要查看脚本运行状况,在脚本最后一行加入pause
引自:http://www.cnblogs.com/sorex/archive/2012/05/16/2502001.html