C#和SystemFileWatcher-多个文件

| 我正在使用
FileSystemWatcher
监视文件夹中的新文件。将新文件复制到其中后,对我来说效果很好。但是,如果我复制5个文件(这将是我一次最多可以复制的文件),它将触发,但是
FileSystemEventArgs
只有一个文件。 我需要它来传递所有新文件。 有没有办法让它处理所有文件,然后循环浏览它们? 这是我的代码:
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);
}
    
已邀请:
如果我没记错的话,观察者会触发多个事件,每个文件触发一个事件。 另请注意:   Windows操作系统在FileSystemWatcher创建的缓冲区中将文件更改通知组件。如果在短时间内有很多更改,缓冲区可能会溢出。这将导致该组件失去对目录更改的跟踪,它将仅提供一揽子通知。使用InternalBufferSize属性增加缓冲区的大小是昂贵的,因为它来自无法调换到磁盘的非分页内存,因此,请使缓冲区尽可能小但又足够大,以免丢失任何文件更改事件。为避免缓冲区溢出,请使用NotifyFilter和IncludeSubdirectories属性,以便可以过滤掉不需要的更改通知。 来源:http://msdn.microsoft.com/zh-CN/library/system.io.filesystemwatcher.aspx     
您需要做两个更改: 增加缓冲区大小。 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();
}     

要回复问题请先登录注册