将 FileSystemWatcher 与 Windows 服务一起使用

Using a FileSystemWatcher with Windows Service

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

这是我的主要服务class。

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()
    {

    }
}

这是我的文件处理器Class

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 一旦超出范围就会被处理掉。解决方案是将其声明为实例变量而不是