Apr
30
2013

C#.Net How To: Monitor Directory and files using C# FileSyestemWatcher

In this article let’s explore the use of C# FileSystemWatcher for monitoring the directory and files. However, before we start; let’s get some basic idea about FileSystemWatcher in C#.

FileSystemWatecher in C#.Net


As name suggests C# FileSystemWatcher watches the Directory or Files for any modification. FileSystemWatcher is a class in .Net derived from System.IO namespace that continuously monitors a specified Directory for file system changes. As soon as the change occurs it automatically raises a corresponding event. These events include Created, Renamed, Changed, Deleted and an Error event. Of course, there are several reasons why one needs File System Watcher in his application. As mentioned above there might be a requirement in application to log a File creation time or deletion time, etc. In short this acts as Directory watcher or File Watcher service.

The file system watcher in C# monitors a specified directory along with files and subdirectories. The C# FileSystemWatcher has a property called “Filter” by which you can filter the files with specific extensions i.e. with the help of wild-card; even you can monitor File attributes like Last Access, Security, Last Write and Size of a file.

Look at the below table for all events that gets raised by FileSystemWatcher while monitoring a specified Directory or file.

Sr. No.
Event Name
Description
1
Created
When a new File or Folder gets created.
2
Renamed
When an existing file or folder gets renamed.
3
Deleted
When an existing file or folder gets deleted.
4
Changed
When an existing file or folder gets modified.
5
Error
When an error occurs.

Now let’s look at the actual implementation of simple FileSystemWatcher. In this example, we will create a new Windows Forms on which user can be able to Select a Folder path to monitor. Please refer below screenshot, this would be our filesystemwatecher application.

Output of C# FileSystemWatcher
Output of FileSystemWatcher in C#.Net

Please note that, We are using Visual Studio 2010 – Windows Form application to demonstrate the C# FileSystemWatcher that will monitor a folder for changes. In fact it monitors Directory, subdirectories along with files in it.

Steps to implement C# FileystemWatcher


  1. Create a new Windows forms project. Specify the project name and click on OK button. Here I am putting a1ashiishFileSystemWatcher as project name.

    WinForms Application for File System Watcher
    New Windows Forms Application for File System Watcher


  2. A Windows Form will appear on screen. Here I have made following changes to default forms property and file names –
    1. Set the “Text” property of the form to “a1ashiish.blogspot.com – FileSystemWatcher”.

    2. Renamed “Form1.cs” to “MainForm.cs”.

      Rename Program.cs to MainForm.cs
      Rename Program.cs to MainForm.cs

    3. Renamed “Program.cs” to “a1ashiishFSWatcher.cs”.

    Note – These changes are not necessary to follow. So you can skip above changes. However, this article is based on above changes only.


  3. Now, put controls on your form as given in below screenshot.

    FileSystemWatcher in C#.Net
    FileSystemWatcher in C#.Net

    Following controls are used in this example –

    Two button controls :

    1. Browse : To browse to the folder needed for monitoring. Internally FolderBrowserDialog control is used. FolderBrowserDialog is c# control that prompts a user to browse & select a folder location, user can also create a new folder in selected location. Click on FolderBrowserDialog to read more on this .Net control.
    2. Start Monitoring : To start the C# FileSystemWatcher. On clicking, this button would start monitoring the specified path. Once, monitoring started the button will be renamed as “Stop Monitoring”.

    Two Label & two TextBox controls :

    1. Folder Path : A textbox next to this label would show the folder path selected through “Browse” button.
    2. File Filter : A textbox allows entering either full file name or wild cards to monitor selected files.

    List box : This list box shows all the events that are raised. No need to place this in Windows Forms at design time. We would create this control at runtime on Form Load event.

  4. In this step we are going to implement a FolderBrowserDialog control to select a folder path to monitor folders/files. On Button_Click event of Browse button write below code –
       private void button1_Click(object sender, EventArgs e)

       {
           // Create FolderBrowserDialog object.
           FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
           // Show a button to create a new folder.
           folderBrowserDialog.ShowNewFolderButton = true;
           DialogResult dialogResult = folderBrowserDialog.ShowDialog();
           // Get selected path from FolderBrowserDialog control.
           if (dialogResult == DialogResult.OK)
           {
               textBox1.Text = folderBrowserDialog.SelectedPath;
               Environment.SpecialFolder root = folderBrowserDialog.RootFolder;
           }
       }

    In above code, we have created an instance of FolderBrowserDialog control that helps us to select a folder location in Windows Explorer navigation style. Click here to know more about the FolderBrowserDialog.

  5. Now it’s time to implement a FileSystemWatcher service. In this step we are going to create an instance of FileSystemWatcher service on Button_Click event of “Start Monitoring” button.
      listBox.Items.Add(“Started FileSystemWatcher Service…”);

      fsWatcher.Path = textBox1.Text;

      // Set Filter.

      fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? “*.*” : textBox2.Text;

      // Monitor files and subdirectories.
      fsWatcher.IncludeSubdirectories = true;

      // Monitor all changes specified in the NotifyFilters.

      fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                               NotifyFilters.CreationTime |
                               NotifyFilters.DirectoryName |
                               NotifyFilters.FileName |
                               NotifyFilters.LastAccess |
                               NotifyFilters.LastWrite |
                               NotifyFilters.Security |
                               NotifyFilters.Size;

      // Watch on events.
      fsWatcher.EnableRaisingEvents = true;

      // Raise Event handlers.

      fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
      fsWatcher.Created += new FileSystemEventHandler(OnCreated);
      fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
      fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
      fsWatcher.Error += new ErrorEventHandler(OnError);
      .
      .
      .

    Complete code is given in step 7.

    Now, what we have done in above code? – We have created an instance of FileSystemWatcher, added a filter to it, specified that we want to include subdirectories in monitoring, specified when to receive the notifications and finally added different event handlers.


  6. Now add Event handler code like below (Refer step 7 for complete code.)

         // FileSystemWatcher – OnCreated Event Handler

          public void OnCreated(object sender, FileSystemEventArgs e)
          {
              // Add event details in listbox.
              this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
          }

  7. Complete Code of “MainForm.cs” is given below –
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Threading;
    namespace a1ashiishFileSystemWatcher
    {
        public partial class MainForm : Form
        {
            public ListBoxlistBox;
            public const String startMonitoring = “Start Minitoring…”;
            public const String stopMonitoring = “Stop Minitoring…”;
            public MainForm()
            {
                InitializeComponent();
                //Create a listBox to show activities of all Events.
                listBox = new ListBox();
                listBox.FormattingEnabled = true;
                listBox.Location = new System.Drawing.Point(23, 121);
                listBox.Name = “listBox”;
                listBox.Size = new System.Drawing.Size(571, 238);
                listBox.TabIndex = 2;
                this.Controls.Add(listBox);
            }
            private voidbutton1_Click(object sender, EventArgs e)
            {
                // Create FolderBrowserDialog object.
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                // Show a button to create a new folder.
                folderBrowserDialog.ShowNewFolderButton = true;
                DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                // Get selected path from FolderBrowserDialog control.
                if (dialogResult == DialogResult.OK)
                {
                    textBox1.Text = folderBrowserDialog.SelectedPath;
                    Environment.SpecialFolderroot = folderBrowserDialog.RootFolder;
                }
            }
            private voidbutton2_Click(object sender, EventArgs e)
            {
                // Create a new FileSystemWatcher object.
                FileSystemWatcher fsWatcher = new FileSystemWatcher();
                switch (button2.Text)
                {
                    // Start Monitoring…
                    case startMonitoring:
                        if (!textBox1.Text.Equals(String.Empty))
                        {
                            listBox.Items.Add(“Started FileSystemWatcher Service…”);
                            fsWatcher.Path = textBox1.Text;
                            // Set Filter.
                            fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? “*.*” : textBox2.Text;
                            // Monitor files and subdirectories.
                            fsWatcher.IncludeSubdirectories = true;
                            // Monitor all changes specified in the NotifyFilters.
                            fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                                                     NotifyFilters.CreationTime |
                                                     NotifyFilters.DirectoryName |
                                                     NotifyFilters.FileName |
                                                     NotifyFilters.LastAccess |
                                                     NotifyFilters.LastWrite |
                                                     NotifyFilters.Security |
                                                     NotifyFilters.Size;
                            fsWatcher.EnableRaisingEvents = true;
                            // Raise Event handlers.
                            fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
                            fsWatcher.Created += new FileSystemEventHandler(OnCreated);
                            fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
                            fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                            fsWatcher.Error += new ErrorEventHandler(OnError);
                            button2.Text = stopMonitoring;
                            textBox1.Enabled = false;
                            textBox2.Enabled = false;
                        }
                        else
                        {
                            listBox.Items.Add(“Please select folder to monitor….”);
                        }
                        break;
                    // Stop Monitoring…
                    case stopMonitoring:
                    default:
                        fsWatcher.EnableRaisingEvents = false;
                        fsWatcher = null;
                        button2.Text = startMonitoring;
                        textBox1.Enabled = true;
                        textBox2.Enabled = true;
                        listBox.Items.Add(“Stopped FileSystemWatcher Service…”);
                        break;
                }
            }
            // FileSystemWatcher – OnCreated Event Handler
            public voidOnCreated(object sender, FileSystemEventArgs e)
            {
                // Add event details in listbox.
                this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
            }
            // FileSystemWatcher – OnChanged Event Handler
            public voidOnChanged(object sender, FileSystemEventArgs e)
            {
                // Add event details in listbox.
                this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
            }
            // FileSystemWatcher – OnRenamed Event Handler
            public voidOnRenamed(object sender, RenamedEventArgs e)
            {
                // Add event details in listbox.
                this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1} to “{2}””, e.FullPath, e.ChangeType, e.Name)); });
            }
            // FileSystemWatcher – OnDeleted Event Handler
            public voidOnDeleted(object sender, FileSystemEventArgs e)
            {
                // Add event details in listbox.
                this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
            }
            // FileSystemWatcher – OnError Event Handler
            public void OnError(object sender, ErrorEventArgse)
            {
                // Add event details in listbox.
                this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Error : {0}”, e.GetException().Message)); });
            }
        }
    }

  8. Once you done with the coding, hit F5 button to execute the program, select a folder path using Browse button, then enter wild cards for file filter (you can skip this step) and clip on “Start Monitoring…” button to monitor the C# FileSystemWatcher service.

In this c# tutorial we learned how to use FileSystemWatcher in c#. If you find the information is worth, then please share the article on your social media because sharing is caring.

More articles –

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

9 Comments+ Add Comment

  • thumbs down

  • Thumbs Up.

  • Nice job. Thanks for posting all the code so I could understand easier. Next I’m going to ftp on the raise event.

  • Thanks, that code helps me a lot ..

  • It works verry well, but I have a probleme with it. Before I go farer I’m C# beginner, and as I was saying, I wan to execute some instructions only when the file is completly copied into the folder being watched.
    I’ll appreciate your answers.

  • Did anyone tried this? This is not working.
    I tried all the code, browse to my desktop…add, edit, renamed, delete files their but nothing is being written in the listbox. In short, this is not monitoring the event/actions happened in the directory that you browsed.

  • thumbs down – seems like some assembly references are missing!!!

  • You are just AWESOME !
    I have been struggling with this since i had to complete my project on time.

    Thumbs Up.

  • Great Article, very fast way to get up to speed with the FileSystemWatcher

    I have a working prototype for my current project in just a few hours.
    Thanks

Leave a comment