Filesystemwatcher detecting File Closing. How ?

S

Sagaert Johan

I have a program that uses the filesystemwatcher.

Problem is that i have to wait until the file is closed before i can do
someting with it in the changed event.

How can i detect if the foreighn application has finished writing and has
closed the file ?


Johan
 
P

Peter Bromberg [C# MVP]

filesystemwatcher can detect if a file has changed, appeared, etc. but you
would likely need to use another method to determine if the file is
"closed".

The first thing that comes to mind is when a new file is detected, to
repeatedly poll to attempt to read from the file and handle the result (nice
if you can do so without using an exception for business logic). Once you
can read from the file, you have a high degree (not 100%) of assurance that
its finished being written.

Maybe somebody else can come up with a more elegant idea.
Peter
 
J

Jeffrey Palermo

I have tackled this exact issue, and there is no built-in way to detect
when the file is free of locks by other processes. Who knows, some
user may have a Word document open and locked in that folder, and your
code needs to be able to handle this situation. Ok, I know that
probably won't happen, but another process has the file locked if it's
still being written. My solution was to listen for FileName and
LastWrite events. I would then attempt to access the file. If it is
locked, you'll just have a try again later. Ahh, but you won't get
another FileSystemWatcher event for that file, so you'll just have to
be innovative. Yes, you can poll and swallow the exceptions that occur
if the file is locked, but be careful that your program doesn't hang if
the file doesn't become unlocked (or if the file is very large).

If only a few files come through, you may want to sent a delegate to
the threadpool to sleep for a second and try to process the file again.
.. . and not give up until it is successful. This way, your main
program can continue to function.

The bottom line is that you will have to be innovative about how you
solve this problem because the solution will have to be unique to your
scenario.

Best regards,
Jeffrey Palermo
Blog: http://www.jeffreypalermo.com
 
S

Sagaert Johan

Solved :

i use


private void fileSystemWatcher1_Changed(object sender,
System.IO.FileSystemEventArgs e)

{

FileStream fs=null;

try

{

fs=new
FileStream(e.FullPath,FileMode.Open,FileAccess.ReadWrite,FileShare.None,100)
;

fs.Close();

Console.WriteLine("closed, ready to process the file ");



}

catch

{

}

}
 

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