Search code examples
c#.netwindowsfilesystemwatcher

FileSystemWatcher Class - Excluding Directories


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();
        }

Solution

  • 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.