Building a File Monitoring Application using FileSystemWatcher


This is essential for tracking file and directory changes, especially in applications requiring real-time updates, such as logging, backup systems, or security software. In this article, we’ll dive into a Windows Form application that uses the FileSystemWatcher class to monitor changes in a specified directory.

Let’s explore the core functionality of this application and how you can use it to detect file events like creation, deletion, renaming, and changes in real-time.

What is FileSystemWatcher?

The FileSystemWatcher class in .NET allows you to monitor changes in the file system. This includes:

  • File/Directory Creation
  • File/Directory Deletion
  • File/Directory Modification
  • File/Directory Renaming

The FileSystemWatcher works by listening to system-level notifications and triggering events when changes occur.

Source code

Click to Expand/Collapse full source code
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;
namespace SystemEyeWatcher
{
	public partial class SystemWatcher : Form
	{
		enum Type
		{
			CREATED,
			CHANGED,
			RENAMED,
			DELETED
		}
		string name = String.Empty;
		public SystemWatcher()
		{
			InitializeComponent();
		}
		private void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
		{
			name = Path.GetFileName(e.FullPath);
			FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ",
			DateTime.Now.ToString(), Type.CHANGED);
		}
		private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
		{
			name = Path.GetFileName(e.FullPath);
			FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
			DateTime.Now.ToString(), Type.CREATED);
		}
		private void Watcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
		{
			name = Path.GetFileName(e.FullPath);
			FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
			DateTime.Now.ToString(), Type.DELETED);
		}
		private void Watcher_Renamed(object sender, System.IO.RenamedEventArgs e)
		{
			FillListWatch(listViewWatch, e.ChangeType.ToString(), e.OldFullPath, 
			e.OldName, e.Name, DateTime.Now.ToString(), Type.RENAMED);
		}
		private void watcherNew_Click(object sender, EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			SystemOptions sysOptions = new SystemOptions();
			sysOptions.ShowDialog();
			Cursor.Current = Cursors.Default;
		}
		private void watchStart_Click(object sender, EventArgs e)
		{
			lblStatus.Text = "Watching...";
			Watcher.Path = <Your Path>
			Watcher.Filter = <???>;
			Watcher.IncludeSubdirectories = true;
			Watcher.EnableRaisingEvents = true;
		}
		private void watchStop_Click(object sender, EventArgs e)
		{
			lblStatus.Text = "Ready...";
			Watcher.EnableRaisingEvents = false;
		}
		private void FillListWatch(ListView listViewWatch,
		string type,
		string objects, 
		string objectname, 
		string newobject, 
		string details, 
		Type objectsType)
		{
			ListViewItem item = new ListViewItem(type);
			item.SubItems.Add(objects);
			item.SubItems.Add(objectname);
			item.SubItems.Add(newobject);
			item.SubItems.Add(details);
			lblWatchType.Text = type;
			lblObjectName.Text = objectname + " : " + newobject;
			lblObjectPath.Text = objects;
			switch (objectsType)
			{
				case Type.CREATED:
					item.ImageIndex = 8;
					item.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
					break;
				case Type.CHANGED:
					item.ImageIndex = 9;
					item.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
					break;
				case Type.RENAMED:
					item.ImageIndex = 6;
					item.BackColor = System.Drawing.Color.FromArgb(128, 255, 128);
					break;
				case Type.DELETED:
					item.ImageIndex = 5;
					item.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
					break;
			}
			listViewWatch.Items.AddRange(new ListViewItem[] { item });
			lblEntries.Text = "Watched Entries : " + listViewWatch.Items.Count;
		}
		private void SystemWatcher_FormClosing(object sender, FormClosingEventArgs e)
		{
			ExitingApplication();
			Application.Exit();
		}
	}
}


Code Breakdown

1. Main Components

  • FileSystemWatcher Initialization: The application sets up a FileSystemWatcher to monitor a directory and respond to events.
  • Event Handlers: The application listens for specific file system events (e.g., Changed, Created, Deleted, Renamed).
  • Dynamic UI Updates: Information about changes is displayed in a ListView with details such as event type, object name, path, and timestamps.

2. Event Handlers

Below are the event handlers for the FileSystemWatcher. These methods are triggered whenever an event occurs.

File Created

private void Watcher_Created(object sender, FileSystemEventArgs e)
{
    name = Path.GetFileName(e.FullPath);
    FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
    DateTime.Now.ToString(), Type.CREATED);
}

File Changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
    name = Path.GetFileName(e.FullPath);
    FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ",
    DateTime.Now.ToString(), Type.CHANGED);
}

File Deleted
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
    FillListWatch(listViewWatch, e.ChangeType.ToString(), e.OldFullPath, 
    e.OldName, e.Name, DateTime.Now.ToString(), Type.RENAMED);
}

File Renamed
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
    FillListWatch(listViewWatch, e.ChangeType.ToString(), e.OldFullPath, 
    e.OldName, e.Name, DateTime.Now.ToString(), Type.RENAMED);
}

3. UI Updates with FillListWatch

The FillListWatch method populates the ListView control with details about the detected event. It color-codes the rows based on event type for better visibility.

private void FillListWatch(ListView listViewWatch,
string type,
string objects, 
string objectname, 
string newobject, 
string details, 
Type objectsType)
{
    ListViewItem item = new ListViewItem(type);
    item.SubItems.Add(objects);
    item.SubItems.Add(objectname);
    item.SubItems.Add(newobject);
    item.SubItems.Add(details);
    lblWatchType.Text = type;
    lblObjectName.Text = objectname + " : " + newobject;
    lblObjectPath.Text = objects;

    switch (objectsType)
    {
        case Type.CREATED:
            item.ImageIndex = 8;
            item.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
            break;
        case Type.CHANGED:
            item.ImageIndex = 9;
            item.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
            break;
        case Type.RENAMED:
            item.ImageIndex = 6;
            item.BackColor = System.Drawing.Color.FromArgb(128, 255, 128);
            break;
        case Type.DELETED:
            item.ImageIndex = 5;
            item.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
            break;
    }

    listViewWatch.Items.Add(item);
    lblEntries.Text = "Watched Entries : " + listViewWatch.Items.Count;
}

4. Starting and Stopping the Watcher

The application provides controls to start and stop the watcher.

  • Start Watching: Enables real-time monitoring by setting the EnableRaisingEvents property to true.
private void watchStart_Click(object sender, EventArgs e)
{
    lblStatus.Text = "Watching...";
    Watcher.Path = "<Your Path>"; // Specify the directory to watch
    Watcher.Filter = "*.*";       // Filter for specific file types
    Watcher.IncludeSubdirectories = true;
    Watcher.EnableRaisingEvents = true;
}

  • Stop Watching: Disables monitoring by setting EnableRaisingEvents to false.
private void watchStop_Click(object sender, EventArgs e)
{
    lblStatus.Text = "Ready...";
    Watcher.EnableRaisingEvents = false;
}

Features

With this application it offers:

  1. Real-time monitoring of a specified directory.
  2. Event Logging: Tracks and logs file changes, including creation, deletion, renaming, and modification.
  3. User Interface: Displays monitored events in a ListView with color-coded rows for different event types.
  4. Custom Event Handling: Uses enumerations for event types to streamline processing.

Sample Use Case

Suppose you have a folder where user uploads are stored. With this, you can:

  1. Track new uploads.
  2. Log file modifications (e.g., overwrites).
  3. Detect unauthorized deletions or changes.

This application demonstrates the power of the FileSystemWatcher class in .NET for monitoring file and directory changes in real time. With its user-friendly UI, real-time logging, and color-coded feedback, this application is a valuable tool for developers and administrators looking to keep track of file system activities.
Previous Post Next Post

نموذج الاتصال