Monday, July 9, 2012

File System Watcher class in .Net (C#)


Sometime you might need to monitor changes like files added, deleted, renamed for particular folder. To do so, .net provides FileSystemWatcher class to monitor such kind of activity for particular folder or file.

FileSystemWatcher class provides some events which are fired when some action done to the folder like file created, deleted, renamed etc. You can also specify filter to file system watcher if you want to watch only text file or music files etc. It also provides an option to include subdirectories to watch or monitor.

Let’s have a look on below code snippet

void FileSystemWatcherDemo_Loaded(object sender, RoutedEventArgs e)
{
    //creates an instance of FileSystemWatcher
    FileSystemWatcher watcher = new FileSystemWatcher();
    //set folder or file path to watch
    watcher.Path = @"D:\Temp\Test";
    //watches txt files only
    watcher.Filter = "*.txt";
    //enable watching subdirectories also
    watcher.IncludeSubdirectories = true;

    watcher.Created += new FileSystemEventHandler(watcher_Created);
    watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
    watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
    watcher.Changed += new FileSystemEventHandler(watcher_Changed);
           
    //starts watching/monitoring folder or file
    watcher.EnableRaisingEvents = true;
}

void watcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File changed - {0}, change type - {1}", e.Name, e.ChangeType);
}

void watcher_Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine("File renamed - old name - {0}, new name - {1}", e.OldName, e.Name);
}

void watcher_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File deleted - {0}", e.Name);
}

void watcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File created - {0}, path - {1}", e.Name, e.FullPath);
}

Output –
File created - Text2.txt, path - D:\Temp\Test\Text2.txt
File created - Text1.txt, path - D:\Temp\Test\Text1.txt
File renamed - old name - Text2.txt, new name - Text3.txt
File deleted - Text3.txt

As per above code, I have chosen Test folder to monitor file system changes. After running this application, if I add, delete, rename any text file to this folder, it will notify FileSystemEvent to raise respective event and the code written in respective event handler will execute.

See Also - 

No comments:

Post a Comment