Friday, August 12, 2016

C# .Net monitor directory file changed created

What does Dropbox use to monitor file changes in the Dropbox folder?

Native Windows applications track directory changes by using the FindFirstChangeNotification / FindNextChangeNotification functions.

https://www.quora.com/What-does-Dropbox-use-to-monitor-file-changes-in-the-Dropbox-folder

As name suggests FileSystemWatcher watches the Directory or Files for any modification. FileSystemWatcher is a class in .Net derived fromSystem.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 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 byFileSystemWatcher 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. 

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

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 ListBox listBox;
        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 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;
            }
        }

        private void button2_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 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)); });
        }

        // FileSystemWatcher - OnChanged Event Handler
        public void OnChanged(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 void OnRenamed(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 void OnDeleted(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, ErrorEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format("Error : {0}", e.GetException().Message)); });
        }

    }
}

Reference:

http://www.csharptutorial.in/2013/04/Csharp.Net-How-To-Monitor-Directory-and-files-using-Csharp-FileSyestemWatcher.html#.U16l0vn3V4A

No comments: