正しく機能しているネットワークでは、イベントの欠落に関連するエラーは発生しないはずですが、ネットワーク上の単純な一時的な中断により、FileSystemWatcherの監視が役に立たなくなることに注意する必要があります。
ネットワーク共有への接続が一時的に切断されると、FileSystemWatcherでエラーが発生し、接続が再確立されても、FileSystemWatcherは通知を受信しなくなります。
これは、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));
}
このコンソールアプリケーションを起動してからネットワーク接続を無効にしようとすると、Win32Exceptionが表示されますが、もう一度実行すると、実行中のFileSystemWatcherによってエラーイベントが表示されなくなります。