.NET filesystemwatcher - 它是文件还是目录?

Arn*_*rno 34 .net c# filesystemwatcher

有没有办法确定FSW是否删除了文件或目录?

Ste*_*dit 40

这是fletcher解决方案的简化和更正版本:

namespace Watcher
{
    class Program
    {
        private const string Directory = @"C:\Temp";
        private static FileSystemWatcher _fileWatcher;
        private static FileSystemWatcher _dirWatcher;

        static void Main(string[] args)
        {
             _fileWatcher = new FileSystemWatcher(Directory);
             _fileWatcher.IncludeSubdirectories = true;
             _fileWatcher.NotifyFilter = NotifyFilters.FileName;
             _fileWatcher.EnableRaisingEvents = true;
             _fileWatcher.Deleted += WatcherActivity;

            _dirWatcher = new FileSystemWatcher(Directory);
            _dirWatcher.IncludeSubdirectories = true;
            _dirWatcher.NotifyFilter = NotifyFilters.DirectoryName;
            _dirWatcher.EnableRaisingEvents = true;
            _dirWatcher.Deleted += WatcherActivity;

            Console.ReadLine();
        }

        static void WatcherActivity(object sender, FileSystemEventArgs e)
        {
            if(sender == _dirWatcher)
            {
                Console.WriteLine("Directory:{0}",e.FullPath);
            }
            else
            {
                Console.WriteLine("File:{0}",e.FullPath);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案没有考虑到`FileSystemWatcher'都在不同的线程上运行.因此,如果监视目录中有很多事件,您在应用中看到的事件顺序可能不同 - 即.您可以记录文件是在尚不存在的目录中创建的,后跟创建所述目录的事件. (3认同)

Yur*_*ich -1

您可以询问该FileSystemEventArgs.FullPath属性来判断它是目录还是文件。

if (Path.GetFileName(e.FullPath) == String.Empty) 
{
    //it's a directory.
}
Run Code Online (Sandbox Code Playgroud)

检查它是文件还是目录。

  • 它被删除了,所以这些调用会失败,不是吗? (3认同)
  • 对于已删除的文件,“File.GetAttributes”会引发“FileNotFoundException”。 (2认同)
  • @Yuriy:正如我一直在说的,事实证明并非如此。我没有相信您对文档的解释或我的记忆,而是只是对其进行了测试。我在“C:\abc”上设置了 FSW 并创建了一个“def”子目录。我发现`e.FullPath`包含“C:\abc\def”。请注意缺少任何尾部反斜杠。 (2认同)