I wanted to try writing a utility similar to Filemon myself – to just trap the FCNs for a particular file or folder. My utility is not superior than Filemon – Filemon is one wonderful tool which helps a lot of people daily in their day-to-day troubleshooting activities.

FileSystemWatcher is a Class in System.IO which helped me doing this. It turned out to be very simple to do this. I can imagine how tough it would’ve been if I’m not in the .NET world and my Visual Studio makes my job more easier with its powerful Intellisense.

Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace FCN
{
    public partial class Form1 : Form
    {
        FileSystemWatcher fsw;
        public Form1()
        {
            InitializeComponent();
            fsw = new FileSystemWatcher();
            fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            fsw.Changed += new FileSystemEventHandler(OnChanged);
            fsw.Created += new FileSystemEventHandler(OnChanged);
            fsw.Deleted += new FileSystemEventHandler(OnChanged);
            fsw.Renamed += new RenamedEventHandler(OnRenamed);
            listBox1.ScrollAlwaysVisible = true;
            listBox1.HorizontalScrollbar = true;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            textBox1.Text = folderBrowserDialog1.SelectedPath;
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            fsw.Path = textBox1.Text;
            fsw.IncludeSubdirectories = true;
            fsw.EnableRaisingEvents = true;
        }
        void OnChanged(object source, FileSystemEventArgs e)
        {
           listBox1.Items.Add("File: " + e.FullPath + " " + e.ChangeType);
        }
 
        void OnRenamed(object source, RenamedEventArgs e)
        {
            listBox1.Items.Add("File: " + e.OldFullPath + " renamed to " + e.FullPath);
        }
    }
}

Very simple code indeed. My Windows form looks like below:

image

Happy Learning!