I am currently trying to exclude directories with the FileSystemWatcher class, although I have used this:
FileWatcher.Filter = "C:\\$Recycle.Bin";
and
FileWatcher.Filter = "$Recycle.Bin";
It compiles ok, but no results are shown when I try this.
If I take the filter out, all files load fine, code is below:
static void Main(string[] args)
{
string DirPath = "C:\\";
FileSystemWatcher FileWatcher = new FileSystemWatcher(DirPath);
FileWatcher.IncludeSubdirectories = true;
FileWatcher.Filter = "*.exe";
// FileWatcher.Filter = "C:\\$Recycle.Bin";
// FileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
FileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
// FileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
// FileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
FileWatcher.EnableRaisingEvents = true;
Console.ReadKey();
}
Nope, filesystemwatchers run on their own thread.
Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.
FileSystemWatcher. This object allows you to be notified when certain events occur in a directory, such as file creation, deletion, or modification.
Determine if the file is a directory in your event handler, and do nothing then:
private void WatcherOnCreated(object sender, FileSystemEventArgs fileSystemEventArgs)
{
if (File.GetAttributes(fileSystemEventArgs.FullPath).HasFlag(FileAttributes.Directory))
return; //ignore directories, only process files
//TODO: Your code handling files...
}
You probably haven't read http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx. You cannot exclude anything with Filter property. It only includes objects matching filter.
If you want exclude something, do it in events fired by FSW.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With