C#: FileWatcher: Filtering multiple files using FileSystemWatcher’s filters

http://forums.asp.net/t/1024002.aspx/1

Example 1:

Filtering multiple files using FileSystemWatcher’s filters

· using System;

· using System.IO;

· using System.Text.RegularExpressions;

·

· class MyWatcher

· {

·

· static void Main(string[] args)

· {

· // if there are no arguments exit

· if (args.Length == 0) return;

·

· FileSystemWatcher objWatcher = new FileSystemWatcher();

· objWatcher.Path = args[0];

· objWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

· objWatcher.Filter = "*.*";

·

· // add event handlers

· objWatcher.Changed += new FileSystemEventHandler(OnChanged);

· objWatcher.Created += new FileSystemEventHandler(OnChanged);

· objWatcher.Deleted += new FileSystemEventHandler(OnChanged);

· objWatcher.Renamed += new RenamedEventHandler(OnChanged);

·

·

· Console.Write("Watching: ");

· Console.WriteLine(args[0]);

·

· Console.WriteLine("Press \’q\’ to quit.");

· Console.WriteLine();

· while (Console.Read() != ‘q’);

· }

·

· private static string getFileExt(string filePath)

· {

· if (filePath == null) return "";

· if (filePath.Length == 0) return "";

· if (filePath.LastIndexOf(".") == -1) return "";

· return filePath.Substring(filePath.LastIndexOf("."));

· }

·

· private static void OnChanged(object source, FileSystemEventArgs e)

· {

· // get the file’s extension

· string strFileExt = getFileExt(e.FullPath);

·

· // filter file types

· if (Regex.IsMatch(strFileExt, @"\.txt)|\.jpg", RegexOptions.IgnoreCase))

· {

· Console.WriteLine("A change has been made to a watched file type.");

· }

· }

·

}

Example 2:

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

Examples

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s