windows FileSystemWatcher 类 - 排除目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6065330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:52:54  来源:igfitidea点击:

FileSystemWatcher Class - Excluding Directories

c#.netwindowsfilesystemwatcher

提问by Ken

I am currently trying to exclude directories with the FileSystemWatcher class, although I have used this:

我目前正在尝试使用 FileSystemWatcher 类排除目录,尽管我已经使用了这个:

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

回答by Tomas Voracek

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.

您可能没有阅读http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx。您不能使用 Filter 属性排除任何内容。它只包括匹配过滤器的对象。

If you want exclude something, do it in events fired by FSW.

如果您想排除某些内容,请在 FSW 触发的事件中进行。

回答by Eternal21

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