【问题标题】:FileSystemWatcher not raising when files are copied or moved to folder [duplicate]将文件复制或移动到文件夹时,FileSystemWatcher 未引发 [重复]
【发布时间】:2012-07-13 18:43:18
【问题描述】:

可能重复:
Detecting moved files using 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);
    }

【问题讨论】:

标签: c# .net filesystemwatcher


【解决方案1】:

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

根据 MSDN

复制和移动文件夹

操作系统和 FileSystemWatcher 对象解释一个 剪切和粘贴操作或移动操作作为文件夹的重命名操作 及其内容。如果您将包含文件的文件夹剪切并粘贴到 被监视的文件夹,FileSystemWatcher 对象只报告 文件夹是新的,但不是它的内容,因为它们本质上只是 改名了。

更多信息请点击here

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

watcher.IncludeSubdirectories=true;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    相关资源
    最近更新 更多