技术探索

创建.NET系统服务程序

2017-04-26
403

1、创建服务项目,会生成一个程序文件如 myService.cs
   C# -> 经典桌面 -> windows服务

2、创建主程序(例如定时服务)

protected override void OnStart(string[] args)
{
 var timer = new System.Timers.Timer();
 timer.Interval = 1000 * 30;
 timer.Elapsed += StartService;
 timer.Enabled = true;
}
private void StartService(object sender,System.Timers.ElapsedEventArgs e)
{
 using (StreamWriter w = new StreamWriter(new FileStream(@"f:\a.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8))
 {
  w.Write(DateTime.Now.ToString() + "\r\n");
  w.Close();
  w.Dispose();
 }
}


3、添加安装程序
   1) 打开myService.cs[设计],在该页空白处右键,然后选择“添加安装程序”
   2) 在 serviceProcessInstall1 的属性中设置 Account = LocalSystem
   3) 如果要开机自动启动,则在 serviceInstall1 的属性中设置 StartType = Automatic

4、生成

5、安装服务

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil e:\bin\Release\myService.exe

6、卸载服务

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil /u e:\bin\Release\myService.exe