Use a FileSystemWatcher object to Monitor all file operations in Application Directory


This example makes use of the following:

  • a FileSystemWatcher object
  • a method for guarding directory against inappropriate files
  • a method for determining if a file is of a type I define in a custom class
  • a custom-defined class against which we'll test


    Scroll down for the code...








    Code for declaring a FileSystemWatcher object at the form-level, and for instantiating it in the form's constructor:

    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Windows.Forms;
    
    namespace Sample{
    
        public partial class Form1 : Form {
    
            FileSystemWatcher fsWatcher = new FileSystemWatcher();
     
            public Form1() {
                InitializeComponent();
                fsWatcher.Path = Application.StartupPath;
                fsWatcher.EnableRaisingEvents = true;
                fsWatcher.SynchronizingObject = this;
                fsWatcher.Created += new FileSystemEventHandler(fsWatcher_Created);
                fsWatcher.Changed += new FileSystemEventHandler(fsWatcher_Changed);
                fsWatcher.Deleted += new FileSystemEventHandler(fsWatcher_Deleted);
            }
    
            void fsWatcher_Deleted(object sender, FileSystemEventArgs e) {
                MessageBox.Show("File '" + e.Name + "' was deleted.");
            }
    
            void fsWatcher_Changed(object sender, FileSystemEventArgs e) {
                MessageBox.Show("The contents of " + e.Name + " were modified.");
            }
    
            void fsWatcher_Created(object sender, FileSystemEventArgs e) {
                MessageBox.Show(e.Name + " was created.");
            }
            
    	}
    }
    

    And here are a couple of other methods I came up with:


    The following method is one I developed so that my event-handler, fsWatcher_Created(), could invoke it. It's purpose is to look through the files in the directory being watched and, if any of them are not Excuse files (there's a clsExcuse.cs file in my project), delete them. Additionally, if any of the files really are Excuse files, but do not have the correct extension, the method messages the user, suggesting that s/he correct this.

            private void bounceMiscreantFiles() {
                int miscreants = 0; //non-Excuse files shouldn't be here, and are therefore "miscreants" :)
                DirectoryInfo di = new DirectoryInfo(selectedFolder);
                FileInfo[] files = di.GetFiles();
                for (int i = 0; i < files.GetUpperBound(0) + 1; i++) {
                    FileInfo fi = new FileInfo(files[i].FullName);
                    if (fi.Extension != ".excuse") {
    					//we know the extension isn't that of an Excuse file (based on class Excuse.cs in my project;
    					//but we need to see if, at the binary level, it IS or ISN'T of type Excuse...
                        if (!fileIsBinarilyAnExcuse(fi.FullName)) {
                            fi.Delete();
                            miscreants++;
                        }
                        else {
                            //wrong extension, but appears, on the binary level, to be a legit Excuse file                  
                            string msg = "File '" + Path.GetFileName(fi.FullName) + "' appears to be a valid Excuse ";
                            msg += "file at the binary level, but has the wrong extension.  It is suggested that you ";
                            msg += "rename the file if you intend to leave it in your Excuses folder.";
                            MessageBox.Show(msg, "File problem");
                        }
                    }
                }
                if (miscreants > 0) {
                    MessageBox.Show(miscreants.ToString() + "\"miscreant\" file(s) deleted from the Excuses folder.");
                }
            }
    


    Now, here is the fileIsBinarilyAnExcuse() method I developed, and upon which the above-delineated bounceMiscreantFiles() method is dependent:

    private bool fileIsBinarilyAnExcuse(string filePath) {
                bool IsExcuse = false;
                if (!File.Exists(filePath)) {
                    MessageBox.Show("'" + filePath + "' doesn't exist!", 
                        "Invalid filePath passed to method fileIsBinarilyAnExcuse()");
                }
                else {
                    try {
                        BinaryFormatter formatter = new BinaryFormatter();
                        Excuse tempExcuse;
                        using (Stream input = File.OpenRead(filePath)) {
    						//if we can successfully cast to an Excuse, 
    						//we know the file is, at the binary level, an Excuse;
    						//for completeness sake I'll show the Excuse class 
    						//code below (on the website page)
                            tempExcuse = (Excuse)formatter.Deserialize(input);
                        }
                        IsExcuse = true;
                    }
                    catch (Exception ex) {
                        int i = ex.Message.IndexOf("Unable to cast object");
                        if (i > -1) {
                            IsExcuse = false;
                            //MessageBox.Show("Wrong cast");
                        }
                    }
                }
                return IsExcuse;
            }
    


    Here is the code for the Excuse class:

        [Serializable]
        class Excuse
        {        
            public string Description { get; set; }
            public string Results { get; set; }
            public DateTime LastUsed { get; set; }
            public string ExcusePath { get; set; }
    
            public Excuse()
            {
                ExcusePath = "";
            }
    
            public Excuse(string excusePath)
            {
                OpenFile(excusePath);
            }
    
            public Excuse(Random random, string folder)
            {
                string[] fileNames = Directory.GetFiles(folder, "*.excuse");
                int noExcuses = fileNames.GetUpperBound(0);
                if (noExcuses > -1) {
                    OpenFile(fileNames[random.Next(fileNames.Length)]);
                }
                else {
                    MessageBox.Show("There are no excuses in the currently selected folder.", "Operation not possible");
                }
            }
    
            private void OpenFile(string excusePath)
            {
                this.ExcusePath = excusePath;
                BinaryFormatter formatter = new BinaryFormatter();
                Excuse tempExcuse;
                using (Stream input = File.OpenRead(excusePath))
                {
                    tempExcuse = (Excuse)formatter.Deserialize(input);
                }
                Description = tempExcuse.Description;
                Results = tempExcuse.Results;
                LastUsed = tempExcuse.LastUsed;
            }
    
            public void Save(string fileName)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                using (Stream output = File.OpenWrite(fileName))
                {
                    formatter.Serialize(output, this);
                }
            }
        }