Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
like image 982
Ken Avatar asked May 19 '11 22:05

Ken


People also ask

Is FileSystemWatcher multithreaded?

Nope, filesystemwatchers run on their own thread.

What is the use of FileSystemWatcher Class in. net framework?

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.

How does FileSystemWatcher work?

FileSystemWatcher. This object allows you to be notified when certain events occur in a directory, such as file creation, deletion, or modification.


2 Answers

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...
}
like image 158
Eternal21 Avatar answered Oct 07 '22 20:10

Eternal21


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.

like image 45
Tomas Voracek Avatar answered Oct 07 '22 21:10

Tomas Voracek