2011-05-15 64 views
0

我正在使用FileSystemWatcher來觀察新文件的文件夾。當一個新文件被複制進去時,它對我來說很好。然而,如果我複製5個文件(這將是我一次做的最大值),它會激發,但FileSystemEventArgs只有一個文件。C#和SystemFileWatcher-多個文件

我需要它通過所有的新文件。

有沒有辦法讓它處理所有的文件,然後我通過它們循環?

這裏是我的代碼:

static void Main(string[] args) 
{ 
    FileSystemWatcher fsw = new FileSystemWatcher(FolderToMonitor) 
           { 
            InternalBufferSize = 10000 
           }; 
    fsw.Created += new FileSystemEventHandler(fsw_Created); 
    bool monitor = true; 

    Show("Waiting...", ConsoleColor.Green); 
    while (monitor) 
    { 
     fsw.WaitForChanged(WatcherChangeTypes.All, 2000); // Abort after 2 seconds to see if there has been a user keypress. 
     if (Console.KeyAvailable) 
     { 
      monitor = false; 
     } 
    } 

    Show("User has quit the process...", ConsoleColor.Yellow); 
    Console.ReadKey(); 
}`   

static void fsw_Created(object sender, FileSystemEventArgs args) 
{ 
    Show("New File Detected!", ConsoleColor.Green); 
    Show("New file name: " + args.Name, ConsoleColor.Green); 

    bool fileIsReadOnly = true; 

    while (fileIsReadOnly) 
    { 
     Thread.Sleep(5000); 
     fileIsReadOnly = IsFileReadonly(args.FullPath); 

     if (fileIsReadOnly) 
      Show("File is readonly... waiting for it to free up...", ConsoleColor.Yellow); 
    } 
    Show("File is not readonly... Continuing..", ConsoleColor.Yellow); 

    HandleFile(args); 
} 
+0

如何複製文件?也許它會以某種方式影響觀察者。 – 2011-05-15 08:46:13

回答

4

如果我沒有記錯,觀察者觸發多個事件,每一個文件。

也注意到這一點:

Windows操作系統通知您的文件更改組件由FileSystemWatcher的創建一個緩衝區。如果短時間內有很多變化,緩衝區可能會溢出。這會導致組件無法跟蹤目錄中的更改,並且只會提供一攬子通知。使用InternalBufferSize屬性增加緩衝區的大小非常昂貴,因爲它來自無法換出到磁盤的非分頁內存,所以請將緩衝區保持爲小但足夠大以便不會錯過任何文件更改事件。爲避免緩衝區溢出,請使用NotifyFilter和IncludeSubdirectories屬性,以便可以過濾掉不需要的更改通知。

來源:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

0

你需要做兩個變化:

  1. 增加緩衝區大小。
  2. EnableRaisingEvents。

請參見下面的修改後的代碼:

static void Main(string[] args) 
{ 
FileSystemWatcher fsw = new FileSystemWatcher(FolderToMonitor) 
          { 
           InternalBufferSize = 65536 
          }; 
fsw.EnableRaisingEvents = true; 
fsw.Created += new FileSystemEventHandler(fsw_Created); 
bool monitor = true; 

Show("Waiting...", ConsoleColor.Green); 
while (monitor) 
{ 
    fsw.WaitForChanged(WatcherChangeTypes.All, 2000); // Abort after 2 seconds to see if there has been a user keypress. 
    if (Console.KeyAvailable) 
    { 
     monitor = false; 
    } 
} 
Show("User has quit the process...", ConsoleColor.Yellow); 
Console.ReadKey(); 

}