文件复制或移动到文件夹时,FileSystemWatcher不会引发

可能重复:
使用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); } 

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

根据MSDN

复制和移动文件夹

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

有关更多信息,请单击此处

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

 watcher.IncludeSubdirectories=true; 

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