C#创建windows服务
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace MyService { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n"); sw.Flush(); sw.Close(); fs.Close(); } //protected override void OnContinue() //{ // base.OnContinue(); //} //protected override void OnPause() //{ // base.OnPause(); // father class method inherit //} //protected override void OnShutdown() //{ // base.OnShutdown(); //} protected override void OnStop() { FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine("WindowsService: Service Stopped" + DateTime.Now.ToString() + "\n"); sw.Flush(); sw.Close(); fs.Close(); } } }
在设计窗口添加安装程序,生成两个文件,修改其启动的服务名称、以及启动方式。
然后找到windows下.NET目录下InstallUtil.exe拖到服务目录下,执行InstallUtil 项目.exe添加服务。
注意:win7以上版本需要管理员权限。