Pages - Menu

FileSystemWatcher - The process cannot access the file 'filepath' because it is being used by another process.

FileSystemWatcher

"The process cannot access the file 'filepath' because it is being used by another process."

One of the famous error of using FileSystemWatcher is the file access issue. It happens because the FileSystemWatcher.Created event is raised and the file copy is still in progress. ie. The event is raised when the watcher is notified with new file creating, but the file is not yet completed with its creation. Make sense?

In the ideal world, the created event should be raised when the object is "created" but it is not. There are many ways to do handle it and has been written by any people. Without spending too much time on this small matter (from my bigger business requirements), I have written an extension method to do it. Simple but effective.


And we will use it like this. In the event handler, we will check if the file is usable before we copy.





Possible Improvement

There are 2 ways I see this. One way to improve this is create your own event handler that will truly raised when an object is "created" completely. That's probably what most people expected.

However, if you go down to my quick solution, you may want to put in a retry count inside the while loop so it will exit gracefully after a number of tries. This is now an infinite loop afterall!!!

No comments:

Post a comment