C#使用Windows Service的简单教程(创建、安装、卸载、调试)

2019-12-30 15:28:05于丽

  c)ServiceName 服务进程名称,安装与卸载服务时的唯一标识。

具体设置如上图所示。

6)创建安装服务批处理文件Install.bat,可以创建记事本,然后修改后缀为bat,记事本内容如下:

%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exeWindowsServiceDemo.exe
Net StartMyService
sc config MyServicestart= auto
pause

注意:记事本另存为时设置编码为ANSI

说明:第二行为启动服务,第三行为设置服务为自动运行,这两行视服务形式自行选择。如果需要查看脚本运行状况,在脚本最后一行加入pause。

7)同理创建卸载服务批处理文件Uninstall.bat,内容如下:

%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe /uWindowsServiceDemo.exe
pause

8)将Install.bat以及Uninstall.bat这两个文件添加到binDebug目录下,此时解决方案的目录结构如下:

C#,Windows,Service

9)写服务代码,以向文本文件写入文本记录系统时间为例:

 


using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;

namespace WindowsServiceDemo
{
 public partial class MyService : ServiceBase
 {
 private Timer time = new Timer();
 public MyService()
 {
 InitializeComponent();
 }

 protected override void OnStart(string[] args)
 {
 #if DEBUG
 if (!Debugger.IsAttached)
 Debugger.Launch();
 Debugger.Break();
 #endif
 WriteLog("服务启动,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn");
 time.Elapsed += new ElapsedEventHandler(MethodEvent);
 time.Interval = 60 * 1000;//时间间隔为2秒钟
 time.Start();
 }

 protected override void OnStop()
 {
 #if DEBUG
 if (!Debugger.IsAttached)
 Debugger.Launch();
 Debugger.Break();
 #endif
 WriteLog("服务停止,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn");
 }

 protected override void OnPause()
 {
 #if DEBUG
 if (!Debugger.IsAttached)
 Debugger.Launch();
 Debugger.Break();
 #endif
 WriteLog("服务暂停,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn");
 base.OnPause();
 }

 protected override void OnContinue()
 {
 #if DEBUG
 if (!Debugger.IsAttached)
 Debugger.Launch();
 Debugger.Break();
 #endif
 WriteLog("服务恢复,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn");
 base.OnContinue();
 }

 protected override void OnShutdown()
 {
 WriteLog("计算机关闭,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn");
 base.OnShutdown();
 }

 private void MethodEvent(object source, System.Timers.ElapsedEventArgs e)
 {
 time.Enabled = false;
 string result = string.Empty;
 try
 {
 //.........
 result = "执行成功,时间:" + DateTime.Now.ToString("HH:mm:ss") + "rn";
 }
 catch (Exception ex)
 {
 result = "执行失败,原因:" + ex.Message + "rn";
 }
 finally
 {
 WriteLog(result);
 time.Enabled = true;
 }
 }
 /// <summary>
 /// 日志记录
 /// </summary>
 /// <param name="logInfo"></param>
 private void WriteLog(string logInfo)
 {
 try
 {
 string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "Logs";
 if (!Directory.Exists(logDirectory))
 {
  Directory.CreateDirectory(logDirectory);
 }
 string filePath = logDirectory + "" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
 File.AppendAllText(filePath, logInfo);
 }
 catch
 { 

 }
 }
 }
}