We can initiate a FileSystemWatcher using any of below.
1. FileSystemWatcher Watcher = new FileSystemWatcher(); //Intializes a new instance of the FileSystemWatcher Class
2. FileSystemWatcher Watcher = new FileSystemWatcher("c:\\"); //Intializes a new instance with a Path property
3. FileSystemWatcher Watcher = new FileSystemWatcher("c:\\","*.txt"); //Intializes a new instance along with a Path and Filter properties
If we initiate it like in 1., we can set the Path and Filter proporties as given below
Watcher.Path = "c:\\";
Watcher.Filter = "*.txt";
Also we have to add followings too.
Watcher.EnableRaisingEvents = true;
Watcher.IncludeSubdirectories = false;
Watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
To access Created, Deleted, Renamed and Changed events, you have to define handlers that automatically call methods in your code when a change occurs. To create a handler, use the following code:
Watcher.Changed += new FileSystemHandler(myWatcher_Changed); //Handler for Changed Event
Watcher.Created += new FileSystemHandler(myWatcher_Created); //Handler for Created Event
Watcher.Deleted += new FileSystemHandler(myWatcher_Deleted); //Handler for Deleted Event
Watcher.Renamed += new RenamedEventHandler(myWatcher_Renamed);//Handler for Renamed Event
Then you can write codes for what you want to do when such event occured as given below
protected void watcher_Created(
object sender, System.IO.FileSystemEventArgs e)
{
//Codings for what you want to do
}
FileSystemWatcher class makes our work easy.
Good Luck !
No comments:
Post a Comment