This example will show messages if there is any file change in the specified folder. But i added a file filter condition for text files(*.txt). So it will monintor only for txt files. The changes like create new file, rename a file, accessing files etc.. will be notified by a message Box.
The following code snippet will create a file watcher and initialize its properties, then enable it for monitoring.
FileSystemWatcher watcher = new FileSystemWatcher(); // Declares the FileSystemWatcher objectwatcher.Path = @"D:\MyDownloads"; // We have to specify the path which has to monitor
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite NotifyFilters.FileName notifyFilters.DirectoryName; // This property specifies which are the events to be monitoredwatcher.Filter = "*.txt"; // Only watch text files.// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
The following code for event handlers:
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
MessageBox.Show("File: "+ e.OldFullPath+" renamed to "+ e.FullPath);
}
FileSystemWatcher watcher = new FileSystemWatcher(); // Declares the FileSystemWatcher objectwatcher.Path = @"D:\MyDownloads"; // We have to specify the path which has to monitor
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite NotifyFilters.FileName notifyFilters.DirectoryName; // This property specifies which are the events to be monitoredwatcher.Filter = "*.txt"; // Only watch text files.// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
The following code for event handlers:
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
MessageBox.Show("File: "+ e.OldFullPath+" renamed to "+ e.FullPath);
}