C#和SystemFileWatcher-多个文件

时间:2011-05-15 08:37:56

标签: c# filesystemwatcher

我正在使用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);
}

2 个答案:

答案 0 :(得分:4)

如果我没记错的话,观察者会触发多个事件,每个事件对应一个事件。

另请注意:

  

Windows操作系统会在FileSystemWatcher创建的缓冲区中通知组件文件更改。如果在短时间内有许多变化,缓冲区可能会溢出。这会导致组件无法跟踪目录中的更改,并且只会提供一揽子通知。使用InternalBufferSize属性增加缓冲区的大小是昂贵的,因为它来自无法换出到磁盘的非分页内存,因此请保持缓冲区尽小但足够大,以免错过任何文件更改事件。要避免缓冲区溢出,请使用NotifyFilter和IncludeSubdirectories属性,以便过滤掉不需要的更改通知。

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

答案 1 :(得分:0)

您需要进行两项更改:

  1. 增加缓冲区大小。
  2. EnableRaisingEvents。
  3. 请参阅以下修改后的代码:

    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();
    

    }