DESKTOP

Watch for File System Changes

9/25/2010 3:20:50 PM
Problem : You want your application to be notified when changes occur in the file system, such as when files are created or modified.

Solution:
Many file systems provide ways for the operating system to notify programs when files and directories change. .NET provides the System.IO.FileSystemWatcher class to listen to these events.


class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: WatchForChanges [FolderToWatch]");
return;
}

System.IO.FileSystemWatcher watcher =
new System.IO.FileSystemWatcher();
watcher.Path = args[0];
watcher.NotifyFilter = System.IO.NotifyFilters.Size |
System.IO.NotifyFilters.FileName |
System.IO.NotifyFilters.DirectoryName |
System.IO.NotifyFilters.CreationTime;
watcher.Filter = "*.*";
watcher.Changed += watcher_Change;
watcher.Created += watcher_Change;
watcher.Deleted += watcher_Change;
watcher.Renamed +=
new System.IO.RenamedEventHandler(watcher_Renamed);

Console.WriteLine(
"Manipulate files in {0} to see activity...", args[0]);

watcher.EnableRaisingEvents = true;

while (true) { Thread.Sleep(1000); }
}

static void watcher_Change(object sender,
System.IO.FileSystemEventArgs e)
{
Console.WriteLine("{0} changed ({1})", e.Name, e.ChangeType);
}

static void watcher_Renamed(object sender,
System.IO.RenamedEventArgs e)
{
Console.WriteLine("{0} renamed to {1}", e.OldName, e.Name);
}
}


Here’s some sample output (during a create, rename, and delete of the file temp.txt):

D:\code\ch11\WatchForChanges\bin\Debug>WatchForChanges.exe d:\
Manipulate files in d:\ to see activity...
temp.txt changed (Created)
temp.txt changed (Changed)
temp.txt renamed to temp.rename
temp.rename changed (Deleted)

You can also call watcher.WaitForChange(), which will wait until something happens before returning, but usually the event-based mechanism will work for you.


Other  
 
Most View
-  Nokia Lumia 810 – T-Mobile (Part 2)
-  Idisk - The Most Versatile Component Of Mobileme (Part 1)
-  10 Simple Steps To Glamour
-  Cooler Master CM Storm Scout 2 Ghost White
-  Building a WPF Application without XAML (part 1)
-  Programming with DirectX : Optimized Drawing - Using a Sprite Object, Text Drawing
-  Chrome - A Free Web Browser
-  Top Tablet Apps – December 2012 (Part 2)
-  Hands Free Photography
-  Silverlight Recipes : Updating the UI from a Background Thread
Top 10
-  Panasonic Lumix G Vario 14-42mm f/3.5-5.6 II Lens (Part 2)
-  Panasonic Lumix G Vario 14-42mm f/3.5-5.6 II Lens (Part 1)
-  Epson EH-TW8100 - Epson Introduces The Inbetweener
-  Epson Stylus Photo 1500W A3+ Wi-Fi Printer
-  OCZ Vertex 4 (256GB) - Hitting The SSD Sweet Spot
-  Plustek OpticFilm 120 Scanner Review (Part 2)
-  Plustek OpticFilm 120 Scanner Review (Part 1)
-  Samsung 840 Series Pro 256GB 2.5 Inch SATA Solid State Drive
-  SanDisk Ultra Plus 256GB - The Cheapest High-End SSD
-  DrawPlus X6 – 64 Bit Support And A New Rendering Engine