Joydip Kanjilal
Contributor

How to work with FileSystemWatcher in C#

opinion
Mar 28, 20174 mins
C#Software Development

The FileSystemWatcher class can be used to monitor changes to file system and trigger events when such changes occur

filesystemwatcher
Credit: IDG

The FileSystemWatcher class in the System.IO namespace can be used to monitor changes to the file system. It watches a file or a directory in your system for changes and triggers events when changes occur.

In order for the FileSystemWatcher to work, you should specify a directory that needs to be monitored. The FileSystemWatcher raises the following events when changes occur to a directory that it is monitoring.

  • Changed: This event is triggered when a file or a directory in the path being monitored is changed
  • Created: This event is triggered when a file or a directory in the path being monitored is created
  • Deleted: This event is triggered when a file or a directory in the path being monitored is deleted
  • Error: This event is triggered there is an error due to changes made in the path being monitored
  • Renamed: This event is triggered when a file or a directory in the path being monitored is renamed

Creating a simple file system watcher in C#

Let’s create a new console application project in Visual Studio to demonstrate how a typical file system watcher works. Note that a better way to use the FileSystemWatcher class would be by using a Windows Service. You can build a Windows Service that uses the FileSystemWatcher class and sends out notifications as and when changes occur to the path being watched.

Anyway, let’s now get into a bit of code now. In the Main method of the Program.cs file, write the following code.

static void Main(string[] args)

        {

            string path = @"D:IDG";

            MonitorDirectory(path);

            Console.ReadKey();

        }

The following code snippet shows how the MonitorDirectory method would look like. This method would be used to monitor a particular directory and raise events whenever a change occurs. The directory path is passed as an argument to the method.

private static void MonitorDirectory(string path)

        {

            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();

            fileSystemWatcher.Path = path;

            fileSystemWatcher.Created += FileSystemWatcher_Created;

            fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;

            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;

            fileSystemWatcher.EnableRaisingEvents = true;

        }

Note how the events are declared and that the EnableRaisingEvents property of the file system watcher object is set to true to enable raising events when a change on the path being monitored occurs. In essence, this starts the actual monitoring — you are informing FileSystemWatcher to start monitoring the path and raise appropriate events henceforth.

For each of the events that you have declared, you should have the respective event handler that gets executed when the event is triggered. Here’s the source code of the event handlers that would be triggered as and when a change to the directory being monitored occurs.

 private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File created: {0}", e.Name);

        }

        private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File renamed: {0}", e.Name);

        }

        private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File deleted: {0}", e.Name);

        }

Here’s the complete source code for your reference.

using System;

using System.IO;

namespace IDGFileSystemWatcher

{

    class Program

    {

        static void Main(string[] args)

        {

            string path = @"D:IDG";

            MonitorDirectory(path);

            Console.ReadKey();

        }

        private static void MonitorDirectory(string path)

        {

            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();

            fileSystemWatcher.Path = path;

            fileSystemWatcher.Created += FileSystemWatcher_Created;

            fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;

            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;

            fileSystemWatcher.EnableRaisingEvents = true;

        }

        private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File created: {0}", e.Name);

        }

        private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File renamed: {0}", e.Name);

        }

        private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)

        {

            Console.WriteLine("File deleted: {0}", e.Name);

        }

    }

}

Assuming that the directory named IDG is available on the D:> drive of your system, run the console application and then create a new file in the IDG directory. You would observe that the name of the newly created file is displayed in the console window. This is because as soon as a new file is created in the directory being monitored (D:IDG in our example), the FileSystemWatcher_Created event is triggered.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author