FileSystemWatcher在文件复制或移动到文件夹时没有响应

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);
    }

你的代码看起来非常类似于MSDN的代码!https://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher.renamed(v=vs.110).aspx - Kairan
1个回答

2
我在我的一个家庭应用程序中使用了FileSystemWatcher。但据我所知,FileSystemWatcher没有任何移动或复制检测事件。
根据MSDN的说法:
剪切和粘贴操作或移动操作被操作系统和FileSystemWatcher对象解释为对文件夹及其内容的重命名操作。如果您将带有文件的文件夹剪切并粘贴到被监视的文件夹中,则FileSystemWatcher对象仅报告该文件夹为新文件夹,而不报告其内容,因为它们实际上只是被重命名。
点击这里了解更多信息。
我的做法是监视父文件夹和子文件夹,并记录其中的每个更改。为了包括子目录,我使用了以下属性。
watcher.IncludeSubdirectories=true;

一些谷歌搜索建议使用定时器来检测变化。但我不知道它有多有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接