C# - Monitoring folder and files

If you want to get a notification whenever a folder or any files is changed, .Net Framework provides a class name FileSystemWatcher to ease your coding. It provides an event for any files that is modified, created or deleted.

FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Path = "C:\Data";
fileWatcher.Filter = "*.txt";
fileWatcher.IncludeSubdirectories = false;
fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
fileWatcher.Changed += new FileSystemEventHandler(OnFileChanged);

The 'Filter' property is used to set what type of file being monitor. If you want to monitor all file types, just change it to "*.*" or you can specify other file type like "*.jpeg", "*.wmv" or others. The 'IncludeSubdirectories' as the name suggested is set to either include the sub directory in FileSystemWatcher monitoring or ignore it. The 'NotifyFilter' is used with Changed event, when the file attribute like last write or file name is change, the Changed event will be invoke. There is also some other event for this class as shown below:

// When a file is created in the folder
fileWatcher.Created += new FileSystemEventHandler(OnFileModified);
// When a file is deleted from the folder
fileWatcher.Deleted += new FileSystemEventHandler(OnFileModified);
// When a file in the folder is renamed
fileWatcher.Renamed += new FileSystemEventHandler(OnFileModified);

fileWatcher.EnableRaisingEvents = true;

private void OnFileModified(object sender, FileSystemEventArgs e)
{
    if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
    {
        ....
    }
}


You must set the 'EnableRaisingEvents' as true to start the FileSystemWatcher.

0 comments:

Post a Comment

top