2011-05-15 67 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(); 

}