在Windows Service中使用FileSystemWatcher [英] Using a FileSystemWatcher with Windows Service

查看:88
本文介绍了在Windows Service中使用FileSystemWatcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a windows service which needs to monitor a directory for files and then move it to another directory. I am using a FileSystemWatcher to implement this.

这是我的主要服务班.

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类

This is my FileProcessor 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个文件正常工作,然后自动停止.是什么使服务自动停止?当我检查事件日志时,没有看到错误或警告!

After I install and start the service, it works fine for 1 file and then stops automatically. What is making the service stop automatically? When I check the event log I don't see an error or warning!

推荐答案

一旦超出范围,您的局部变量fp就会被清除.解决方案是将其声明为实例变量

Your local variable fp get disposed off once it goes out of scope. The solution is to declare it as an instance variable instead

这篇关于在Windows Service中使用FileSystemWatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆