简体   繁体   中英

Filter FileSystemWatcher changed events

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?

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
}

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.

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)))
   { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM