2012-07-13 79 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提示。但我不知道它有多有效。

相關問題