FileSystemWatcher :files still open

S

Sagaert Johan

Hi

I use the FileSystemWatcher to detect creation of files.
As soon as the event fires i do something with the file, but i sometimes get
a sharing error.
I noticed that when the event fires the watched file is still open (written
to ).
How can i detect if the file has been closed so my app can continue to use
it ?

Johan
 
A

Ashish Das

a crud solution (as i do not have time to send you the code), put your
access to the file code in while loop and check if you can read the file or
not else keep on looping until the file is completely written and you stop
getting share violation. Other way could be that FSW throws minimum 2
events, first at write time and second when file is complete. start your
process on second event throw. you will have to filter the event in FSW for
that. Last way could be that you can check if file is locked or not before
accessing it. if it is locked you can't do anything with it.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

AFAIK there is not a 100% sure solution for this, the problem is that the
file may be still be used by the creator, or maybe it's already in use in
your application, FileSystemWatcher has the nasty behavior of firing more
than one events sometimes, especially if you handle the created|modified
events.

You could avoid the creator interference by calling Thread.Sleep for a
certain amount of time

You could avoid the reentrance in your program by using a flag some other
mechanism to detect if you just handled that file.

IT does depend of your code.


Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top