Sunday, April 6, 2008

How to listen file change notification.

        When we want to receive a notifications about file system changes, we can use class FileSystemWatcher.

Code sample:

string testFolder = Path.GetTempPath();
string testFilePath = Path.Combine(testFolder, "test.tst");
File.Delete(testFilePath);

using (FileSystemWatcher watcher = new FileSystemWatcher(testFolder, "*.tst"))
{
watcher.NotifyFilter =
NotifyFilters.LastAccess | NotifyFilters.LastWrite |
NotifyFilters.FileName | NotifyFilters.DirectoryName |
NotifyFilters.CreationTime | NotifyFilters.Attributes |
NotifyFilters.Size | NotifyFilters.Security;
watcher.Created += OnFileChanged;
watcher.Changed += OnFileChanged;
watcher.Deleted += OnFileChanged;
watcher.EnableRaisingEvents = true;

File.WriteAllText(testFilePath, "text");
File.AppendAllText(testFilePath, "additional text");
File.Delete(testFilePath);
}




Output window content:



FileSystemWatcherOutputContent



Notes:



Unfortunately, my experience shows, that FilesystemWatcher doesn't work absolutely correct. In many cases, it doesn't catch a file changing.



Reference:



FileSystemWatcher Class

No comments: