C# FileSystemWatcher, How to know file copied completely into the watch folder

后端 未结 7 1212
予麋鹿
予麋鹿 2020-12-06 20:14

I am developing a .net application, where I am using FileSystemWatcher class and attached its Created event on a folder. I have to do action on this event (i.e. copy file to

7条回答
  •  猫巷女王i
    2020-12-06 20:35

    It is indeed a bummer that FileSystemWatcher (and the underlying ReadDirectoryChangesW API) provide no way to get notified when a new file has been fully created.

    The best and safest way around this that I've come across so far (and that doesn't rely on timers) goes like this:

    Upon receiving the Created event, start a thread that, in a loop, checks whether the file is still locked (using an appropriate retry interval and maximum retry count). The only way to check if a file is locked is by trying to open it with exclusive access: If it succeeds (not throwing an IOException), then the File is done copying, and your thread can raise an appropriate event (e.g. FileCopyCompleted).

提交回复
热议问题