C# FileSystemWatcher listens to the file system and places a watch on a directory, its subdirecttories, and files and notifies if any changes are made to the directory. This class is useful when you need to auto update the updates in a directory. For example, if you want to create an auto backup of a folder, you can implement a File system watcher service that watches a directory or entire machine and find when and what changes are made and copy the changes to the backup device.
C# FileSystemWatcher acts as a watchdog for file system changes and raises an event when a change occurs. You must specify a directory to be monitored. The class can monitor changes to subdirectories and files within the specified directory. If you have Windows 2000 or later OS, you can even monitor a remote system for changes. The option to monitor files with specific extensions can be set using the Filter property of the FileSystemWatcher class. You can also fine-tune FileSystemWatcher to monitor any change in file Attributes, LastAccess, LastWrite, Security, and Size data.
The FileSystemWatcher class raises the events described in Table 1.
Table 1. FileSystemaWatcher class events
Here is a complete console application that shows how to use the FileSystemWatcher in C#. The code also implements its events. You can use the same code in a Windows Service to schedule it automatically to watch a directory. The FileSystemWatcher is defined in the System.IO namespace. Make sure to import this namespace before you use the class.
Listing 1. Using the FileSystemWatcher Class using C#
- using System;
- using System.IO;
- public class FileWatcher
- {
- public static void Main(string[] args)
- {
-
- if (args.Length != 1)
- {
-
- Console.WriteLine("Usage: FileWatcher.exe <directory>");
- return;
- }
- try
- {
-
- FileSystemWatcher watcher = new FileSystemWatcher();
- watcher.Path = args[0];
-
- watcher.IncludeSubdirectories = true;
-
-
- watcher.NotifyFilter = NotifyFilters.Attributes |
- NotifyFilters.CreationTime |
- NotifyFilters.DirectoryName |
- NotifyFilters.FileName |
- NotifyFilters.LastAccess |
- NotifyFilters.LastWrite |
- NotifyFilters.Security |
- NotifyFilters.Size;
-
- watcher.Filter = "*.*";
-
- watcher.Changed += new FileSystemEventHandler(OnChanged);
- watcher.Created += new FileSystemEventHandler(OnChanged);
- watcher.Deleted += new FileSystemEventHandler(OnChanged);
- watcher.Renamed += new RenamedEventHandler(OnRenamed);
-
- watcher.EnableRaisingEvents = true;
-
-
- DirectoryInfo d1 = new DirectoryInfo(args[0]);
-
- d1.CreateSubdirectory("mydir");
-
- d1.CreateSubdirectory("mydir1\\mydir2\\mydir3");
-
- Directory.Move(d1.FullName + "file://mydir1//mydir2//mydir3",
- d1.FullName + "\\mydir\\mydir3");
-
- if (Directory.Exists(d1.FullName + "\\mydir1"))
- {
-
-
-
- Directory.Delete(d1.FullName + "\\mydir1", true);
- }
-
- DirectoryInfo[] d2 = d1.GetDirectories();
-
- foreach (DirectoryInfo d in d2)
- {
- if (d.Name == "mydir")
- {
-
- Directory.Delete(d.FullName, true);
- }
- }
-
- Console.WriteLine("Press \'q\' to quit the sample.");
- Console.WriteLine();
-
- while (Console.Read() != 'q') ;
- }
- catch (IOException e)
- {
- Console.WriteLine("A Exception Occurred :" + e);
- }
- catch (Exception oe)
- {
- Console.WriteLine("An Exception Occurred :" + oe);
- }
- }
-
- public static void OnChanged(object source, FileSystemEventArgs e)
- {
-
- Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
- }
- public static void OnRenamed(object source, RenamedEventArgs e)
- {
-
- Console.WriteLine(" {0} renamed to {1}", e.OldFullPath, e.FullPath);
- }
- }
The above code starts with the parameter obtained from the user in the form of a path to a directory. Then it creates a FileSystemWatcher instance to monitor all changes in files and directories. Once the FileSystemWatcher is enabled, we are ready to make some changes. In this example, a file and few directories are created and later deleted. Figure 2 contains the output displayed on the console screen.
Figure 2: Output of the FileWatcher class
As you can see, the FileSystemWatcher captured every change made. If you start Windows Explorer and browse the directory you have provided as the parameter, you will find that every change you make in Explorer is reflected in the console. Since input is obtained from the user, chances are high that invalid arguments could raise exceptions; therefore, all the file manipulation code is placed within the try-catch block.
Some Notes
Here are some important notes when using the FileSystemWatcher class.
- Hidden files are not ignored.
- In some systems, FileSystemWatcher reports changes to files using the short 8.3 file name format. For example, a change to "LongFileName.LongExtension" could be reported as "LongFil~.Lon".
- This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands.
- The maximum size you can set for the InternalBufferSize property for monitoring a directory over the network is 64 KB.
IOException Class
The IOException class is the base class for exceptions under the System.IO namespace. All other exceptions under this namespace-DirectoryNotFoundException, EndOfStreamException, FileNotFoundException, and FileLoadException-derive from the IOException class. I/O operations deal with various resources like hard disk, floppy disk, and network sockets, which have a greater chance of failing. Therefore, you should always encapsulate your I/O code within the trycatch block to intercept any exceptions that might occur.
Conclusion
Hope this article have helped you in understanding FileSystemWatcher and IOException Class in C#.
Here are some more practical examples of FileSystemWatcher.