简体   繁体   English

为什么我的FileSystem Watcher不触发事件?

[英]Why is my FileSystem Watcher not firing events?

I create a FileSystemWatcher on a separate thread to monitor a directory for changes. 我在单独的线程上创建FileSystemWatcher,以监视目录中的更改。 None of my events fire when I add a new file or copy a new file into the directory that I am trying to monitor. 当我添加新文件或将新文件复制到我要监视的目录中时,不会触发任何事件。 I've used the FileSystemWatcher class successfully in Windows Forms apps, so I am guessing I am missing something simple. 我已经在Windows Forms应用程序中成功使用了FileSystemWatcher类,所以我想我缺少了一些简单的东西。

public partial class MainWindow : Window
{

    System.IO.FileSystemWatcher watcher;
    public MainWindow()
    {
        InitializeComponent();
        System.Threading.Thread t1 = new System.Threading.Thread(MonitorDir);
        t1.IsBackground = true;
        t1.Start();
    }

    private void MonitorDir()
    {

        watcher = new System.IO.FileSystemWatcher("C:\\Temp","*.*");
        watcher.Created += Watcher_Created;
        watcher.Disposed += Watcher_Disposed;
        watcher.Error += Watcher_Error;
        watcher.Changed += Watcher_Changed;
        while (true)
        {

        }
    }

    private void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void Watcher_Error(object sender, System.IO.ErrorEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void Watcher_Disposed(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        throw new NotImplementedException();
    }
}

您需要将其EnableRaisingEvents属性设置为true (默认情况下为false ),否则它不会引发任何事件。

watcher.EnableRaisingEvents = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM