将FileSystemWatcher与Windows服务一起使用

我有一个Windows服务,需要监视目录中的文件,然后将其移动到另一个目录。 我正在使用FileSystemWatcher来实现这一点。

这是我的主要服务类。

public partial class SqlProcessService : ServiceBase { public SqlProcessService() { InitializeComponent(); } protected override void OnStart(string[] args) { FileProcesser fp = new FileProcesser(ConfigurationManager.AppSettings["FromPath"]); fp.Watch(); } protected override void OnStop() { } } 

这是我的FileProcessor类

 public class FileProcesser { FileSystemWatcher watcher; string directoryToWatch; public FileProcesser(string path) { this.watcher = new FileSystemWatcher(); this.directoryToWatch = path; } public void Watch() { watcher.Path = directoryToWatch; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.*"; watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.EnableRaisingEvents = true; } private void OnChanged(object sender, FileSystemEventArgs e) { File.Copy(e.FullPath, ConfigurationManager.AppSettings["ToPath"]+"\\"+Path.GetFileName(e.FullPath),true); File.Delete(e.FullPath); } } 

安装并启动服务后,它适用于1个文件,然后自动停止。 是什么让服务自动停止? 当我检查事件日志时,我没有看到错误或警告!

一旦它超出范围,你的局部变量fp就会被处理掉。 解决方案是将其声明为实例变量