FileSystemWatcher不触发事件 [英] FileSystemWatcher not firing events

查看:138
本文介绍了FileSystemWatcher不触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我的FileSystemWatcher不会触发任何事件.我想知道何时在目录中创建,删除或重命名新文件.我已经检查了_myFolderPath的设置正确.

For some reason, my FileSystemWatcher is not firing any events whatsoever. I want to know any time a new file is created, deleted or renamed in my directory. _myFolderPath is being set correctly, I have checked.

这是我当前的代码:

public void Setup() {
    var fileSystemWatcher = new FileSystemWatcher(_myFolderPath);
    fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | 
      NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    fileSystemWatcher.Changed += FileSystemWatcherChanged;
    fileSystemWatcher.Created += FileSystemWatcherChanged;
    fileSystemWatcher.Deleted += FileSystemWatcherChanged;
    fileSystemWatcher.Renamed += FileSystemWatcherChanged;

    fileSystemWatcher.Filter = "*.*";
    fileSystemWatcher.EnableRaisingEvents = true;
}

private void FileSystemWatcherChanged(object sender, FileSystemEventArgs e)
{
    MessageBox.Show("Queue changed");
    listBoxQueuedForms.Items.Clear();
    foreach (var fileInfo in Directory.GetFiles(_myFolderPath, "*.*", SearchOption.TopDirectoryOnly))
    {
        listBoxQueuedForms.Items.Add(fileInfo));
    }
}

推荐答案

您似乎在setup方法中将FileSystemWatcher创建为本地变量.当然,这将在方法结束时超出范围,并且很可能会在此时进行整理,从而删除手表.

You seem to be creating the FileSystemWatcher as a local variable in the setup method. This will of course go out of scope at the end of the method and may well be getting tidied up at that point, thus removing the watches.

尝试在将要保留的FSW(例如程序级变量)的位置创建FSW,然后查看是否可以将您分类.

Try creating the FSW at a point where it will be persisted (eg a program level variable) and see if that sorts you out.

这篇关于FileSystemWatcher不触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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