3

可能重复:
使用 FileSystemWatcher 检测移动的文件

我正在寻找一种解决方案来监视目录并在新文件移入目录时通知我的应用程序。显而易见的解决方案是使用 .NET 的 FileSystemWatcher 类。

但问题是,它会引发一个事件,即在文件夹中创建/删除一个新文件,但在将文件移动/复制到文件夹中时不会引发事件。

谁能告诉我这种行为的原因是什么。

我的代码是

static void Main(string[] args)
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void Run()
    {
        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"D:\New folder";
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

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

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Define the event handlers.
    private static 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);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
4

1 回答 1

2

我在我的一个 Home 应用程序中使用了 FileSystemWatcher。但据我所知,FileSystemWatcher 没有任何移动或复制检测事件。

根据 MSDN

复制和移动文件夹

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

欲了解更多信息,请单击此处

我所做的是监视父文件夹和子文件夹并记录其中的所有更改。为了包含子目录,我使用了以下属性。

watcher.IncludeSubdirectories=true;

一些谷歌搜索建议使用计时器来检测更改。但不知道效果如何。

于 2012-07-13T10:37:54.250 回答