I create a FileSystemWatcher on a separate thread to monitor a directory for changes. 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.
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();
}
}
You need to set its EnableRaisingEvents
property to true
(it's false
by default), otherwise it won't raise any events.
watcher.EnableRaisingEvents = true;