9

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();
        }
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
Ken
  • 157
  • 2
  • 5
  • You can exclude files and directories from logging or triggering alerts read out https://medium.com/@srivishnu.k90/powershell-script-to-monitor-file-and-folder-changes-with-email-alert-5276eddb93a9 – srivishnu Mar 18 '20 at 05:02

2 Answers2

12

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.

Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41
  • 1
    Crazy stuff, actualy I had, I was just wondering if there was an alternate root, thanks for your help though! :) – Ken May 19 '11 at 22:24
4

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...
}
Eternal21
  • 4,190
  • 2
  • 48
  • 63