FileSystemWatcher: file used by another process

  • Thread starter Thread starter Oleg Ogurok
  • Start date Start date
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.
 
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
 
Back
Top