Search code examples
c#.netregexfilesystemwatcher

FileSystemWatcher specific files with filename keywords filter


I am using below code for watching files on local system using FileSystemWatcher class. What I would like to do is watch only those filename which I specify in keywords (could be a comma separated string or txt file). Please guide me in the right direction.

   FileSystemWatcher objWatcher = new FileSystemWatcher(); 
   objWatcher.Filter = "*.*"; 
   objWatcher.Changed += new FileSystemEventHandler(OnChanged); 

   private static void OnChanged(object source, FileSystemEventArgs e) 
   { 
     string strFileExt = getFileExt(e.FullPath); 
   } 

Thanks & Regards


Solution

  • While the FileSystemWatcher doesn't support that, you can get that functionality by filtering the filename after the event is raised. You wont be able to use a filter like "." but for example if you wanted all xml and txt files you could do {".xml", ".txt"}

    FileSystemWatcher objWatcher = new FileSystemWatcher(); 
    objWatcher.Changed += new FileSystemEventHandler(OnChanged); 
    
    string[] filters = new string[] { "test", "blah", ".exe"}; //this needs to be a member of the class so it can be accessed from the Changed event
    
    private static void OnChanged(object source, FileSystemEventArgs e) 
    { 
        if (filters.Any(e.FullPath).Contains))
        {     
            string strFileExt = getFileExt(e.FullPath); 
        }
    }
    

    This should give you a basic idea of how you might do it.