Please navigate to the bottom of the page for Table of Contents

Friday, May 27, 2011

How to monitor file system changes using FileSystemWatcher in C#

Many times your code has to monitor changes made to the file system for new or modified files in order to perform certain operations. For example, you may have a notification service that monitors a particular folder for new images added to that directory. Another way to put this question can be: How can you notify users (subscribers) when a particular txt file has been updated in a particular directory?

.NET provides a FileSystemWatcher object defined in the System.IO namespace. let’s review a function that will enable you to monitor a directory for changes.

using System;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// enable watching
DirectoryWatcher(@"C:\Windows");

// again, stupid code to just keep the function alive
while (true) { Thread.Sleep(1000); }
}


public static void DirectoryWatcher(string directoryToWatch)
{
// check incoming arguments
if (string.IsNullOrWhiteSpace(directoryToWatch))
throw new ArgumentNullException("directoryToWatch");

// create a new FileSystemWatcher
FileSystemWatcher w = new FileSystemWatcher();

// set the directory to watch
w.Path = directoryToWatch;

//this is the heart - setup multiple filters
// to watch various types of changes to watch
w.NotifyFilter = NotifyFilters.Size |
NotifyFilters.FileName |
NotifyFilters.DirectoryName |
NotifyFilters.CreationTime;

// setup which file types do we want to monitor
w.Filter = "*.*";

// setup event handlers to watch for changes
w.Changed += watcher_Change;
w.Created += watcher_Change;
w.Deleted += watcher_Change;
w.Renamed += new RenamedEventHandler(watcher_Renamed);

// just some debugging
Console.WriteLine(
"Manipulate files in {0} to see activity...", directoryToWatch);

// enable watching by allowing events to be raised
w.EnableRaisingEvents = true;
}

static void watcher_Change(object sender,
FileSystemEventArgs e)
{
Console.WriteLine("{0} changed ({1})", e.Name, e.ChangeType);
}
static void watcher_Renamed(object sender,
RenamedEventArgs e)
{
Console.WriteLine("{0} renamed to {1}", e.OldName, e.Name);
}
}
}


This is a very basic example on how to use the file system watcher. The key elements you should note and read more about are the NotifyFilter, Filter and the different notification events (Changed, Created, Deleted, Renamed, etc.).

15 comments:

  1. A couple of questions.
    What drives the FileSystemWatcher? Is it the local machine or can a domain also use this?

    Does it work on a local directory only or does it also work across a network? Will my program running locally be able to detect changes across and network?

    Thanks
    -adam

    ReplyDelete
  2. Yes, a FileSystemWatcher can be used to watch files on a local computer, a network drive or a remote computer. Of course, the account running the program needs to have access to the remote systems.

    ReplyDelete
  3. Please Update this Blog & Please Add more ++++++++++++++++++++++++++++++++++++++)
    is a Request for today & Always -------------------------------------------------------------------------->
    With Regards ################

    ReplyDelete

  4. Entretenido juego del estilo pares de animales en el que vas a
    deber formar conjuntos de por lo menos 3 mascotas
    juntas. Tas Murah Admiring the effort and time you put into your site and in depth information you present.
    Souvenir Pernikahan Unik dan Undangan Murah di Jogja It’s good to come across a blog every every now and then that isn’t the same old rehashed information.
    Souvenir Pernikahan Unik dan Undangan Murah di Jogja Fantastic post! Souvenir Pernikahan Unik dan Undangan Murah di Jogja
    I’ve bookmarked your website as well as I’m adding your RSS feeds to my Google account. Souvenir Pernikahan Unik dan Undangan Murah di Jogja se efectuaron en el año 776 Estos últimos son una de las razones por las cuales Farmerama es el favorito de los juegos de animales para sus
    usuarios.

    ReplyDelete
  5. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
    best budget ultrawide monitor

    ReplyDelete
  6. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.

    runkeeper

    ReplyDelete
  7. Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, 4kcomputermonitor.com

    ReplyDelete
  8. The LCD monitor is one of the most fragile and expensive parts of the computer, thus, it pays to handle it with care.4k vs 144hz: What's the best

    ReplyDelete
  9. Hence it is better you have to affiliated understand when setting up. It is easy to put up a lot better apply for right away. http://gecey.com/24-inch-tv/

    ReplyDelete
  10. This is a great article thanks for sharing this informative information. I will visit your blog regularly for some latest post. I will visit your blog regularly for Some latest post. Best 4k monitor 2019

    ReplyDelete
  11. I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. Best 240HZ Monitor:[G-Sync, FreeSync, Budget] 2019 Updated

    ReplyDelete
  12. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. Map network drive

    ReplyDelete