使用FileSystemWatcher检测文件夹重命名

时间:2018-07-03 11:42:14

标签: c# directory filesystemwatcher

我有一个基于文件的应用程序。除了目录重命名之外,FileSystemWatcher可以很好地用于我的大多数用途。这是代码示例:

   class Program
{
    static void Main(string[] args)
    {
        var directoryWatcher = new FileSystemWatcher("D:\\Test")
        {
            NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.Attributes | NotifyFilters.FileName | NotifyFilters.LastAccess |
                              NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size,
            Filter = "*.*"
        };
        directoryWatcher.EnableRaisingEvents = true;
        directoryWatcher.IncludeSubdirectories = true;
        directoryWatcher.Changed += FolderChanged;
        directoryWatcher.Created += FolderCreated;
        directoryWatcher.Deleted += FolderDeleted;
        directoryWatcher.Renamed += FolderRenamed;
        Console.ReadLine();
    }

    private static void FolderRenamed(object sender, RenamedEventArgs e)
    {
    }

    private static void FolderDeleted(object sender, FileSystemEventArgs e)
    {
    }

    private static void FolderCreated(object sender, FileSystemEventArgs e)
    {
    }

    private static void FolderChanged(object sender, FileSystemEventArgs e)
    {
    }
}

在d:\ Test里面有一个文件夹。一旦我重命名,它什么也不会发生。我什么也没收到。

有什么想法吗?

谢谢

授予

1 个答案:

答案 0 :(得分:3)

您的代码还可以,但是您缺少通知者

 watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

还有

// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);

在这里查看完整的代码示例
https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.renamed(v=vs.110).aspx