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(strin开发者_开发问答g[] 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();
}
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.
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...
}
精彩评论