I need to watch a folder (on a network share) and be notified when a filename changes and the file is moved to a sub directory (all one event). This event occurs maybe twice a day. I will have multiple FileSystemWatchers
to watch multiple folders for the same thing.
However, FileSystemWatcher
is notoriously bad for missing events and I cannot have that happen. I've tried replicating the environment and it seems to work however I don't know whether that's because I am doing something in particular.
If I watch for only OnRenamed
events, am I still likely to have issues or can I be sure that I won't miss events?
In a correctly working network, you should not have any error related to missing events, but you should be aware that a simple hiccup on you network will render your FileSystemWatcher monitoring useless.
A momentary drop in the connection to the network share will trigger an Error in your FileSystemWatcher and even if the connection will be reestablished, the FileSystemWatcher will no longer receive any notification.
This is a sligtly adapted example found on MSDN
static void Main()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"\\yourserver\yourshare";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add handler for errors.
watcher.Error += new ErrorEventHandler(OnError);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
private static void OnError(object source, ErrorEventArgs e)
{
// Show that an error has been detected.
Console.WriteLine("The FileSystemWatcher has detected an error");
// Give more information if the error is due to an internal buffer overflow.
Type t = e.GetException().GetType();
Console.WriteLine(("The file system watcher experienced an error of type: " +
t.ToString() + " with message=" + e.GetException().Message));
}
If you try to start this console application and then disable your network connection, you will see the Win32Exception, but if you do it again, no more error event will be seen by the running FileSystemWatcher