Search code examples
c#.netfilesystemsfilesystemwatcher

C#: Monitoring copied or moved files with FileSystemWatcher


I have come across several "solutions" here and across the web but none seem to fit the bill.

What I am looking to do is have an app monitor a folder for new files (either by creation, a move, or a copy) and perform actions on those objects. That being the scenario, I turned to the FileSystemWatcher class to perform this action.

The problem is that the file FileSystemWatcher.Created event is fired before the entire file is created (most noticeably seen through a copy of a large file).

Is there any way to have this event fire at the conclusion of the file creation as opposed to the beginning? I have tried various combination's of the FileSystemWatcher.NofityFilter property with no success.

Thanks in advance! :)


Solution

  • I have used a couple of solutions for this situation.

    1. If you can work with the creator of the file and use a renaming scheme for the file. EG. Create the File as __Name_ while being created and at the end of the process rename it to Name and the event will fire and you have a complete file.

    2. When your trigger fires check if you can get an exclusive readonly lock on the file. If you can then the write operation has been completed to the file. (I wrote something about this in another question Keep settings in sync between forms application and windows service (or any n-tier, really))

    You could possibly integrate something like #2 into your Changed Event and then you'll get the result.