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

时间:2017-04-17 10:55:12

标签: c# wpf filesystemwatcher

我在一个单独的线程上创建一个FileSystemWatcher来监视目录是否有变化。当我添加新文件或将新文件复制到我要监视的目录中时,我的所有事件都不会触发。我在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();
    }
}

1 个答案:

答案 0 :(得分:2)

您需要将EnableRaisingEvents property设置为true(默认情况下为false),否则不会提出任何事件。

watcher.EnableRaisingEvents = true;