Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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 some other location). When I am putting a large size into the attached watch folder the event raised immediately even the file copy process still not completed. I don’t want to check this by file.open method.

Is there any way get notify that my file copy process into the watch folder has been completed and then my event get fire.

like image 746
user446526 Avatar asked Nov 25 '10 14:11

user446526


3 Answers

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).

like image 160
gstercken Avatar answered Oct 14 '22 10:10

gstercken


I have had the exact same problem, and solved it this way:

  1. Set FileSystemWatcher to notify when files are created and when they are modified.
  2. When a notification comes in:

    a. If there is no timer set for this filename (see below), set a timer to expire in a suitable interval (I commonly use 1 second).

    b. If there is a timer set for this filename, cancel the timer and set a new one to expire in the same interval.

When a timer expires, you know that the associated file has been created or modified and has been untouched for the time interval. This means that the copy/modify is probably done and you can now process it.

like image 44
Jon Avatar answered Oct 14 '22 12:10

Jon


You could listen for the modified event, and start a timer. If the modified event is raised again, reset the timer. When the timer has reached a certain value without the modify event being raised you can try to perform the copy.

like image 42
Moo-Juice Avatar answered Oct 14 '22 12:10

Moo-Juice