FileSystemWatcher issues

蓝咒 提交于 2019-12-18 09:17:26

问题


I am trying to use the FileSystemWatcher - and am having some luck..

The goal is to MOVE the file that gets created, from the monitored folder, to a new folder.

But... have hit 2 snags. Firstly, if I move 3 files into a folder at once (Select 3 files, ctrl+x, and then ctrl+c into my Monitor Folder), the monitor only triggers for the first file. The other 2 don't get processed.

            FileSystemWatcher fsw = new FileSystemWatcher(FolderToMonitor);
        fsw.Created += new FileSystemEventHandler(fsw_Created);

        bool monitor = true;

        while (monitor)
        {
            fsw.WaitForChanged(WatcherChangeTypes.All, 2000);
            if (Console.KeyAvailable)
            {
                monitor = false;
            }
        }

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

Is there a way to make it see all 3?

Secondly, if I move a file into the monitor folder, from a different drive, it takes a few seconds to copy the file into the folder. However, the monitor triggers as soon as the file starts copying in.. so therefore, is read only, and not ready to be moved.

Is there a way I can wait for the file to complete it's copy into the monitor folder, before I process it?


回答1:


According to the msdn documentation:

The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

Perhaps that explains your issue?
Also note that cutting and pasting files from one directory to another is basically a mere renaming operation, therefore you should use the Renamed event to detect them.

As for your other problem: try using the Changed event together with Created, as I believe both will be raised exactly once for a file (note that moving a file from another drive in not a simple renaming operation: it's copy and delete), so the Changed event should indicate when the file copy operation has been completed (i.e. it won't fire until the file is complete).



来源:https://stackoverflow.com/questions/6000856/filesystemwatcher-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!