2012-07-13 83 views
2

可能重复不涨价:
Detecting moved files using FileSystemWatcherFileSystemWatcher的当文件被复制或移动到文件夹

我一直在寻找一个解决方案来观看目录,并通知我的应用程序,每当一个新的文件被移动到目录中。明显的解决方案是使用.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); 
    } 
+0

您的代码看起来与MSDN代码非常相似! https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.renamed(v=vs.110).aspx – Kairan 2015-05-03 16:14:00

回答

1

我用FileSystemWatcher的在我的主页应用之一。但根据我的知识,FileSystemWatcher没有任何移动或复制检测事件。

作为每MSDN

复制和移动文件夹

操作系统和FileSystemWatcher的对象解译 剪切和粘贴操作或移动动作为文件夹 一个重命名操作及其内容。如果切割和文件的文件夹粘贴到一个文件夹 正在注视下,FileSystemWatcher的对象仅报告 文件夹如新,而不是它的内容,因为它们基本上只 改名。

欲了解更多信息,请点击here

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

watcher.IncludeSubdirectories=true; 

一些使用计时器检测变化的Google提示。但我不知道它有多有效。

相关问题