简体   繁体   中英

FileSystemWatcher - 3 events during File copy

Is that, every time FileSystemWatcher will generate 3 events when a file is copied to the FileWatcher folder

Example : Am getting Created - > Changed -> Changed (during new file) Or Changed - > Changed - > Changed (during overwrite of existing file) event , when file is copied to the FileWatcher folder using File.Copy(source,watcherFolder,true).

Am getting 3 events when copying file of different size (1kb , 67kb, 100MB, 500MB, 1 GB files). i have registerd for Created and Changed event in FileSystemWatcher

If your question is about the multiple events you are receiving, this is a normal behavior. File copy can raise multiple event.

You can check the changes in FileSystemEventArgs.ChangeType and ignore some of the events. Here is the WatcherChangeTypes Enumeration .

Take a look at FileSystemWatcher Remarks.

About the Created event, it will be raised in the destination folder.

For example, you create two instances of FileSystemWatcher. FileSystemWatcher1 is set to watch "C:\\My Documents", and FileSystemWatcher2 is set to watch "C:\\Your Documents". If you copy a file from "My Documents" into "Your Documents", a Created event will be raised by FileSystemWatcher2, but no event is raised for FileSystemWatcher1. Unlike copying, moving a file or directory would raise two events. From the previous example, if you moved a file from "My Documents" to "Your Documents", a Created event would be raised by FileSystemWatcher2 and a Deleted event would be raised by FileSystemWatcher1.

As mentioned in the comments, you should look for a file being created and then attempt a file lock to determine if it is fully copied.

    while ($true)
    {
        try{ 
            [IO.file]::openwrite("<insert file path>").close()
            break
        }
        catch { start-sleep -Seconds 60 }
    }

If you are in control of the file copy operation, a simple thing to do is to create the file with a temporary name and rename it once it has been copied. Let the FileSystemWatcher watch for the Rename event. This event is fired only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM