HTML clipboard
You can monitor the File system using the System.IO.FileSystemWatcher class. And
you can handle the events like created, changed, deleted, and renamed.
Some important properties of FileSystemWatcher class:
Property |
Description
|
Path |
You can set the path which you want to
monitor. |
Filter |
You can filter the files.
You can specify which files you want to monitor.
If you want to monitor all files you can use assign by "*.*"; |
IncludeSubdirectories |
It takes Boolean value. You want to
monitor only a specified path or you want to monitor all the
subdirectories and files which is specified by path. |
EnableRaisingEvents |
It takes Boolean value. It enables the
raising events. By defaults it is false. You want to handle event on
file system changes, you must set this property to true. |
Let we see the code snippet:
using
System.IO;
private void
Form1_Load(object sender,
EventArgs e)
{
FileSystemWatcher fsw =
new
FileSystemWatcher();
fsw.Path = "c:\\temp\\";
fsw.EnableRaisingEvents = true;
fsw.Filter = "*.*";
fsw.IncludeSubdirectories = true;
fsw.Created += new
FileSystemEventHandler(file_handler_function);
fsw.Changed += new
FileSystemEventHandler(file_handler_function);
fsw.Deleted += new
FileSystemEventHandler(file_handler_function);
fsw.Renamed += new
RenamedEventHandler(file_rename_handler_function);
}
private void
file_rename_handler_function(object sender,
RenamedEventArgs e)
{
Console.WriteLine("File
Name is changed from " + e.OldFullPath + "
to " + e.FullPath);
}
private void
file_handler_function( object sender,
FileSystemEventArgs e)
{
if (e.ChangeType ==
WatcherChangeTypes.Created)
{
MessageBox.Show("New
file created : " + e.FullPath);
}
else if
(e.ChangeType == WatcherChangeTypes.Deleted)
{
MessageBox.Show("File
is deleted : " + e.FullPath);
}
else if
(e.ChangeType == WatcherChangeTypes.Changed)
{
MessageBox.Show("File
modified : " + e.FullPath);
}
}