[C# – I/O] Monitoring the File System

You can browse directories and files programmatically using the “DirectoryInfo” and “FileInfo” classes. But this is the snapshot of the specific moment. What if you want to monitor the changes of files and folders (created, updated, renamed …)

 

1. FileSystemWatcher Class

The “System.IO.FileSystemWatcher” class is responsible for listening to the file system changes and raising events.

– Constructor –

  • public FileSystemWatcher()
  • public FileSystemWatcher(string path)
  • public FileSystemWatcher(string path, string filter)

– Properties –

  • string Path { get; set; }: the path of the directory to watch
  • bool IncludeSubdirectories { get; set; }: indicating whether subdirectories should be monitored; the default is false
  • string Filter { get; set; }: the filter string used to determine what files are monitored in a directory, Filter accepts wildcards for matching files such as “*.txt” or “Sales201?.xml” …
  • NotifyFilters NotifyFilter { get; set; }: the type of changes to watch for
  • bool EnableRaisingEvents { get; set; }: indicating whether the component will raise the events; the default is false

– Events –

  • event FileSystemEventHandler Changed: occurs when a file or directory is changed
  • event FileSystemEventHandler Created: occurs when a file or directory is created
  • event FileSystemEventHandler Deleted: occurs when a file or directory is deleted.
  • event RenamedEventHandler Renamed: occurs when a file or directory is renamed.

Note that the “NotifyFilter” property is used which type of changes you can watch. The “NotifyFilters” enum is also a flag so that you can combine the types together.

  • FileName: the name of the file
  • DirectoryName: the name of the directory
  • Attributes: the attributes of the file or folder
  • Size: the size of the file or folder
  • LastWrite: the date the file or folder last had anything written to it
  • LastAccess: the date the file or folder was last opened
  • CreationTime: the time the file or folder was created
  • Security: the security settings of the file or folder

 

2. How to use FileSystemWatcher

To monitor the file system, you need to do the following tasks

  • Create an instance of “FileSystemWatcher
  • Set the “Path” to be monitored
  • Set the “Filter” property if you want to monitor only specific types of files
  • Set the “NotifyFilter” property
  • Set the “IncludeSubdirectories” property to true if you want to monitor subdirectories too
  • Create event handlers
  • Add event handler to the events
  • Set the “EnableRaisingEvents” property to true to begin monitoring

 

3. Event Handlers – FileSystemEventHandler

When the file/folder is created, changed, or deleted, you can use the “FileSystemEventHandler” delegate as a handler.

  • delegate void FileSystemEventHandler(Object sender, FileSystemEventArgs e)

The “FileSystemEventArgs” provides the following properties:

  • WatcherChangeTypes ChangeType { get; }: Created, Deleted, Changed, Renamed, or All
  • string FullPath { get; }: the fully qualified path of the affected file or directory
  • string Name { get; }: the name of the affected file or directory

 

4. Event Handlers – RenamedEventHandler

When the file/folder is renames, the “RenamedEventHandler” is used instead of “FileSystemEventHandler

  • delegate void RenamedEventHandler( Object sender,  RenamedEventArgs e )

The “RenamedEventArgs” class inherits from “FileSystemEventArgs“. The additional properties are:

  • string OldFullPath { get; }: the previous fully qualified path
  • string OldName { get; }: the previous  name

The “FullPath” and “Name” properties represent the new path and name.

 

5. Example

Let’s monitor “*.txt” files in the “C:\temp” folder. Run the following code and modify text files in the folder and look at how those changes are monitored.


public static void Watch()
{
  string path = @"C:\temp";
  var fsw = new FileSystemWatcher();
  fsw.Path = path;
  fsw.Filter = "*.txt";
  fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.LastAccess;
  fsw.IncludeSubdirectories = false;

  fsw.Created += new FileSystemEventHandler(fsw_Changed);
  fsw.Changed += new FileSystemEventHandler(fsw_Changed);
  fsw.Deleted += new FileSystemEventHandler(fsw_Changed);
  fsw.Renamed += new RenamedEventHandler(fsw_Renamed);

  fsw.EnableRaisingEvents = true;
  while (Console.Read() != 'q') ;
}

static void fsw_Changed(object sender, FileSystemEventArgs e)
{
  Console.WriteLine(e.Name + ": " + e.ChangeType.ToString());
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
  Console.WriteLine("{0}: from {1} to {2}", e.ChangeType.ToString(), e.OldName, e.Name);
}
This entry was posted in C# and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s