FileSystemWatcher: file used by another process

O

Oleg Ogurok

Hi all,

It looks like FileSystemWatcher's Created event can be triggered while a
created file is still in use. For example, if I copy a file into the watched
directory, the event is triggered but then I have to wait for the copy
process to finish copying. If I try to open it, I get a mscorlib exception
saying "file is used by another process"

Is there a way to check whether or not the file is still in use?

Thanks,
--Oleg.
 
M

Morten Teinum

You don't get the message when the file close - so you must poll the file
for an exclusive lock. If you can't open the file - let the thread sleep and
try again.

If you can controll the host application, you can use named events to
synchronize the two applications.

This example tries to lock the file and return a read only stream:

<example>

Stream stream = null;

for ( int i=0; i < maxPollCount; i++)
{
try
{
if ((stream = File.Open(path, FileMode.Open, FileAccess.Read,
FileShare.None)) != null)
break;
}
catch (IOException ex)
{
System.Threading.Thread.Sleep( 1000 );
}
}

if ( stream == null )
throw new ApplicationException("can't open file");

use file and close stream

</example>


/Morten
 

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