服务开发注意事项:
1、在Service1的设计视图上右键添加installer,生成的服务才能安装
2、installer的账户设为LocalSystem最好,若为LocalService则启动后没有被其他应用使用的话会立即停止,若为User则需要设置用户名和密码
3、服务中Environment.CurrentDirectory指向的是System32文件夹,若要获取当前文件夹则要使用AppDomain.CurrentDomain.BaseDirectory
4、记录异常事件可以使用EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error),在计算机-管理-系统工具-事件查看器-Windows日志-应用程序中可以查看
5、安装服务需要使用InstallUtil.exe工具,一般在C:\Windows\Microsoft.Net\Framework64\v4.0.30319文件夹下,管理员权限打开cmd.exe转到该目录下,使用InstallUtil.exe D:\WindowsService1.exe安装服务,使用InstallUtil.exe /u D:\WindowsService1.exe卸载服务
6、必须关掉“服务”窗口才能完成服务的卸载
service设计界面上添加FileSystemWatcher组件,service代码如下:
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;
namespace WindowsService1
{
//注意事项:
//1、在Service1的设计视图上右键添加installer,生成的服务才能安装
//2、installer的账户设为LocalSystem最好,若为LocalService则启动后没有被其他应用使用的话会立即停止,若为User则需要设置用户名和密码
//3、服务中Environment.CurrentDirectory指向的是System32文件夹,若要获取当前文件夹则要使用AppDomain.CurrentDomain.BaseDirectory
//4、记录异常事件可以使用EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error),在计算机-管理-系统工具-事件查看器-Windows日志-应用程序中可以查看
//5、安装服务需要使用InstallUtil.exe工具,一般在C:\Windows\Microsoft.Net\Framework64\v4.0.30319文件夹下,管理员权限打开cmd.exe转到该目录下,使用InstallUtil.exe D:\WindowsService1.exe安装服务,使用InstallUtil.exe /u D:\WindowsService1.exe卸载服务
//6、必须关掉“服务”窗口才能完成服务的卸载
public partial class Service1 : ServiceBase
{
string logfile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log.txt");//Environment.CurrentDirectory指向System32文件夹,不适用
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
fileSystemWatcher1.Path = AppDomain.CurrentDomain.BaseDirectory; //必须在指定Filter和NotifyFilter前指定,否则监控路径为空会抛出异常
fileSystemWatcher1.Filter = "test.txt";//"*.*"//监控任意文件
fileSystemWatcher1.NotifyFilter = System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName;
fileSystemWatcher1.Created += FileSystemWatcher1_Created;
fileSystemWatcher1.Deleted += FileSystemWatcher1_Deleted;
fileSystemWatcher1.Renamed += FileSystemWatcher1_Renamed;
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);//在计算机-管理-系统工具-事件查看器-Windows日志-应用程序中可以查看
File.AppendAllText(logfile, $"Exception\r\nMessage:{ex.Message}\r\n{ex.ToString()}");
}
}
private void FileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
File.AppendAllText(logfile, $"File Created.\r\nFile Name:{e.Name}\r\n");
}
private void FileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
File.AppendAllText(logfile, $"File Deleted.\r\nFile Name:{e.Name}\r\n");
}
private void FileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
{
File.AppendAllText(logfile, $"File Rename.\r\nFile Name:{e.OldName} -> {e.Name}\r\n");
}
protected override void OnStop()
{
}
}
}