Skip to content
Amal Hashim
All posts
Snippet

C# FileSystemWatcher

A console sample that uses FileSystemWatcher to log a timestamp every time a file changes.

1 min read#.NET#C#

FileSystemWatcher raises events when files in a folder change. This console sample watches log.txt and appends the time of each change to a history file.

csharp
using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher("c:\\LogFiles\\", "log.txt");
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.EnableRaisingEvents = true;
            Console.ReadLine();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                using (TextWriter writer = new StreamWriter("C:\\ModifiedHistory.txt", true))
                {
                    writer.WriteLine(DateTime.Now.ToString());
                }
            }
        }
    }
}

Nothing is raised until EnableRaisingEvents is set to true. Console.ReadLine() keeps the program alive while it waits for changes.

Example

Edit and save c:\LogFiles\log.txt twice. C:\ModifiedHistory.txt gets a line for each change (an editor may raise the event more than once per save):

text
16/10/2012 09:14:02
16/10/2012 09:15:41