The ‘FileSystemWatcher’ class is very useful when it comes to monitor a file system path for changes such as create, update and delete of directories/files.
Create an object from the FileSystemWatcher class. (You need to add the ‘System.IO’ namespace)
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
And set the following properties. For this example we will only consider about text files (.txt)
fileSystemWatcher.Filter = "*.txt";
fileSystemWatcher.Path = @"D:\";
fileSystemWatcher.EnableRaisingEvents = true;
And add the following event handlers and create events.
fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed);
And create the following events
static void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e) {
Console.WriteLine("{0} - {1}",e.ChangeType,e.FullPath);
}
static void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}
static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}
static void fileSystemWatcher_Created(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}
Execute this and create, change, rename and delete a text file. And above mentioned events will be invoked.
No comments:
Post a Comment