Reputation: 1
I'm writing C# and using to FileSystemWatcher to monitor a directory of folders (folders can be Created and Renamed). I'm successfully processing the Created and Renamed events.
The contents of these folders can constantly change. But the ONLY change that I need to be cognizant of is when a new HTML file is added to the folder.
How do I filter out all Change Events except for the new [HTML] file?
Upvotes: 0
Views: 1127
Reputation: 50215
Just subscribe to the Change event and filter appropriately with your existing FSW. If you can create another FSW, then Paul Kearney's answer will be sufficient and likely much cleaner.
string[] desiredExtensions = new [] { ".html", ... };
string desiredExtension = ".html";
watcher.Changed += watcher_Changed;
...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
// single
if (string.Equals(Path.GetExtension(e.FullPath), desiredExtension, StringComparison.CurrentCultureIgnoreCase))
{ ... }
// several
if (desiredExtensions.Any(ext => string.Equals(Path.GetExtension(e.FullPath), ext, StringComparison.CurrentCultureIgnoreCase)))
{ ... }
}
Upvotes: 0
Reputation: 6554
FileSystemEventArgs
contains a property called Name
that will help you filter.
http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs.aspx
Quick sample:
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler((o,s) => {
if (s.Name.ToLower().EndsWith(".html") || s.Name.ToLower().EndsWith(".htm"))
Console.WriteLine("HTML is here");
});
Console.ReadLine();
}
Note that you could pass in "*.html" to the constructor, but you would not be capturing files ending in .htm files, which are considered valid. But I'm not sure if that meets your use case.
Upvotes: 0
Reputation: 5533
You can specify a wildcard in the constructor for the type of files to watch for:
var folder = @"c:\";
FileSystemWatcher watcher = newFileSystemWatcher(folder, "*.html");
Then, if you only want to be notified when those files are created:
watcher.Created += new FileSystemEventHandler(watcher_FileCreated);
void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
// do something interesting
}
Upvotes: 1