Marius

Marius

  • NA
  • 17
  • 11.8k

FileSystemWatcher and reading from file

Jun 10 2011 12:23 PM
So, my situation is something like this:

What I want to do is to detect when the contents of a file change, and then read from that file (and use the data for whatever). The trouble is, when I try to do that, I get a "File is in use" exception.

Some code:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Path = pathToFile;
watcher.Filter = fileName;

//then the event:

watcher.Changed = new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;

//and the handler

void watcher_Changed(object sender, FileSystemEventArgs e)
{
        FileStream fs = new FileStream(pathToFile + fileName, FileMode.Open, FileAccess.Read);

        //read from file, etc etc
}


So, this basically says that the file cannot be accessed because it's open by another process. I assume the FileStream locks the file or something like that?
It works when not trying to read from the file...

Anyway I can fix this?

Thanks in advance.






Answers (15)