I have a FileSystemWatcher monitoring a file on a network share. If an event occurs to make the share unavailable, maybe due to a network problem, the FileSystemWatcher becomes
Wouldn't something like this work? Seems to work for my simple test case.
var fsw = new FileSystemWatcher("[folder]", "*.*") { IncludeSubdirectories = true};
var fsw_processing = false;
fsw.Deleted += (s, e) =>
{
fsw_processing = true;
fsw.EnableRaisingEvents = false;
//......
fsw.EnableRaisingEvents = true;
fsw_processing = false;
};
fsw.Changed += (s, e) =>
{
fsw_processing = true;
fsw.EnableRaisingEvents = false;
//......
fsw.EnableRaisingEvents = true;
fsw_processing = false;
};
//governor thread to check FileSystemWatcher is still connected.
//It seems to disconnects on network outages etc.
Task.Run(() =>
{
while (true)
{
if (fsw.EnableRaisingEvents == false && fsw_processing == false)
{
try
{fsw.EnableRaisingEvents = true;}
catch (Exception) { fsw.EnableRaisingEvents = false; }
}
System.Threading.Thread.Sleep(1000 * 10);//sleep 10 secs
}
});
A couple of comments and suggestions...(which grew and grew as I was typing...sorry)
The FileSystemWatcher.Error event is fired when the FileSystemWatcher gets so many events happening so quickly that it can't handle them all. It doesn't get fired when an error occurs in watching the file system (such as the network dropping out).
I believe I've had a similar situation. The problem is that when the network connection drops out, the FileSystemWatcher will never have an event triggered, because it actually can't see what it's supposed to be watching, but it doesn't seem to be aware of the fact. When the network connection comes back, the FileSystemWatcher doesn't recover - i.e. it still can't see the (restored) connection. The only solution that we came up with that seemed to work reliably was to have a timer that regularly dropped the whole FileSystemWatcher object and created a new one, setting all of the events and watch folder etc. Since dropping and creating a new FileSystemWatcher is (relatively) quick (i.e. milliseconds) you could set the timer to activate every 10 seconds or so without using up too much of the processor. Of course, if the network is still out, the FileSystemWatcher is not going to be able to see the network no matter what you do. But that's OK, it will try again in another 10 seconds.
Two things to watch out for with this solution:
I hope that helps.
Follow-up in this. At the suggestion of a Microsoft resource on the MSDN forums, I added this to Microsoft Connect.
Key points from the feedback from Microsoft: - Error event is not only for internal buffer overflows - They will add the possibility of exposing the stopListening property to their list of customer suggestions
Link here: http://connect.microsoft.com/VisualStudio/feedback/details/727934/filesystemwatcher-error-handling