.net FileSystemWatcher不会获取已移动的文件夹

时间:2016-03-30 01:25:33

标签: c# .net windows filesystemwatcher

我发现有很多关于移动文件的讨论(我没有遇到任何问题),但没有任何特定的移动文件夹(因此这篇文章)。

我有一个FileSystemWatcher实例化如下:

  var fileWatcher = new FileSystemWatcher("C:\\mypath");
  fileWatcher.IncludeSubdirectories = true;
  fileWatcher.NotifyFilter = NotifyFilters.LastWrite
                               | NotifyFilters.FileName
                               | NotifyFilters.CreationTime
                               | NotifyFilters.Size;
   fileWatcher.Changed += OnChanged;
   fileWatcher.Created += OnChanged;
   fileWatcher.Deleted += OnDeleted;
   fileWatcher.Renamed += OnRenamed;
   fileWatcher.Error += WatcherOnError;
   fileWatcher.EnableRaisingEvents = true;

无论我对文件做什么,我都会按预期获得事件,但是如果我拖动(移动)文件夹(甚至包含文件)到监视文件夹,没有这些事件都得到了提升。

我在Windows 10上运行(不确定其他版本的win是否也采用相同的方式)。

有谁知道如何获取文件夹移动的通知?

2 个答案:

答案 0 :(得分:2)

您通过在NotifyFilters.DirectoryName中不包含NotifyFilter来明确排除目录更改。

这里是文档的link,但它只是暗示:-)我通过使用你的代码而不是使用额外的标志来确认它。

答案 1 :(得分:1)

奇怪,这对我有用:

void Main()
{
    FileSystemWatcher fsw = new FileSystemWatcher(@"c:\Temp\");
    fsw.IncludeSubdirectories = true;
    fsw.Changed += new FileSystemEventHandler(OnChanged);
    fsw.EnableRaisingEvents = true;

    while (true) { }
}

void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
    Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}