9

如果文件被创建、复制或移动到我正在观看的目录中,我会尝试收到通知。我只想收到有关文件的通知,而不是目录。

这是我目前拥有的一些代码:

_watcher.NotifyFilter = NotifyFilters.FileName;
_watcher.Created += new FileSystemEventHandler(file_created);
_watcher.Changed += new FileSystemEventHandler(file_created);
_watcher.Renamed += new RenamedEventHandler(file_created);
_watcher.IncludeSubdirectories = true;
_watcher.EnableRaisingEvents = true;

问题是,如果我移动一个包含文件的目录,我不会收到该文件的任何事件。

如何让它通知我添加(无论如何)到监视目录或其子目录的所有文件?

万一我解释得不够好……我有WatchedDirectoryDirectory1Directory1包含Hello.txt。如果我将Directory1移动到WatchedDirectory,我希望收到有关Hello.txt的通知。

编辑:我应该注意我的操作系统是 Windows 8。我确实收到了复制/粘贴事件的通知,但没有移动事件(拖放到文件夹中)。

4

3 回答 3

4

也许这种解决方法可能会派上用场(但我会小心性能,因为它涉及递归):

private static void file_created(object sender, FileSystemEventArgs e)
{
    if (e.ChangeType == WatcherChangeTypes.Created)
    {
        if (Directory.Exists(e.FullPath))
        {
            foreach (string file in Directory.GetFiles(e.FullPath))
            {
                var eventArgs = new FileSystemEventArgs(
                    WatcherChangeTypes.Created,
                    Path.GetDirectoryName(file),
                    Path.GetFileName(file));
                file_created(sender, eventArgs);
            }
        }
        else
        {
            Console.WriteLine("{0} created.",e.FullPath);
        }
    }
}
于 2013-04-30T13:58:18.180 回答
4

将更多过滤器添加到您的NotifyFilters. 目前您只关注文件名的变化。这与您的 Changed 和 Renamed 处理程序一起应该可以完成这项工作。

_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite

这似乎仅适用于复制/粘贴操作。对于剪切/粘贴操作(或拖放),也添加以下通知过滤器:NotifyFilters.DirectoryName.

编辑

我已经玩过它了,实际上只有一个顶级文件夹的通知进来。如果你想到它,这是有道理的。由于创建了更改类型,因此您确定其中的所有文件和文件夹都是新的,您可以处理它们。

因此,@AlexFilipovici 的方法是唯一可行的方法,尽管我会将结果(文件夹)排入队列并在工作线程(或任务,等等)上处理它。您不希望在 FSWatcher 事件处理程序中花费太多时间,尤其是在文件以高速率传入的情况下。

于 2013-04-30T14:02:38.630 回答
1

复制和移动文件夹

操作系统和 FileSystemWatcher 对象将剪切和粘贴操作或移动操作解释为文件夹及其内容的重命名操作。如果您将包含文件的文件夹剪切并粘贴到正在监视的文件夹中,则 FileSystemWatcher 对象仅将文件夹报告为新文件夹,而不报告其内容,因为它们实际上只是被重命名。

参考:MSDN

于 2013-04-30T14:00:59.420 回答