FileSystemWatcher problem

M

Marek

Hello.

I'm using FileSystemWatcher to monitor creation of files
in specified directory and its subdirectories:

dirWorks = new DirectoryWorks (strDirName);
FileSystemWatcher watcher = new FileSystemWatcher
(strDirName);
watcher.IncludeSubdirectories = true;
watcher.Created += new FileSystemEventHandler
(dirWorks.OnCreated);
watcher.EnableRaisingEvents = true;

In the OnCreated event handler, I need to open the
created file and read from it:

public void OnCreated (object sender, FileSystemEventArgs
e)
{
...
try
{
file = new FileInfo (e.FullPath);
fstream = file.Open (FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite);

stream = new StreamReader (fstream);

for (string line = stream.ReadLine (); line != null;
line = stream.ReadLine ())
{
Console.WriteLine (line);
}
}
catch (Exception ex)
{
...
}
...
}

But I often (not always) get this exception:

Unhandled Exception: System.IO.IOException: The process
cannot access the file "5\msg002.txt" because it is being
used by another process.

Why? The only way I can block this exception is to sleep
this thread [I put this code at the beginning of
OnCreated event handler]:

Thread.Sleep (1000);

Why this prevents the exception to occur?

Thanks for help!

Marek
 
P

Patrick Steele [MVP]

Unhandled Exception: System.IO.IOException: The process
cannot access the file "5\msg002.txt" because it is being
used by another process.

Why? The only way I can block this exception is to sleep
this thread [I put this code at the beginning of
OnCreated event handler]:

Thread.Sleep (1000);

Why this prevents the exception to occur?

My guess is you're getting the File creation method as soon as the file
is created (and probably still in use by the process that created it).
You put a sleep in there and give the other process a chance to finish
up and close the file and you then can access the file.
 

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