How to set filter for FileSystemWatcher for multiple file types?

半世苍凉 提交于 2019-11-28 06:08:26

There is a workaround.

The idea is to watch for all extensions and then in the OnChange event, filter out to desired extensions:

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

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)|\.doc", RegexOptions.IgnoreCase)) 
    { 
        Console.WriteLine("watched file type changed."); 
    } 
} 
Anders Abel

You can't do that. The Filter property only supports one filter at a time. From the documentation:

Use of multiple filters such as *.txt|*.doc is not supported.

You need to create a FileSystemWatcher for each file type. You can then bind them all to the same set of FileSystemEventHandler:

string[] filters = { "*.txt", "*.doc", "*.docx", "*.xls", "*.xlsx" };
List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();

foreach(string f in filters)
{
    FileSystemWatcher w = new FileSystemWatcher();
    w.Filter = f;
    w.Changed += MyChangedHandler;
    watchers.Add(w);
}

To expand on Mrchief's and jdhurst's solution:

private string[] extensions = { ".css", ".less", ".cshtml", ".js" };
private void WatcherOnChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
{
    var ext = (Path.GetExtension(fileSystemEventArgs.FullPath) ?? string.Empty).ToLower();

    if (extensions.Any(ext.Equals))
    {
        // Do your magic here
    }
}

This eliminates the regex checker (which in my mind is too much overhead), and utilizes Linq to our advantage. :)

Edited - Added null check to avoid possible NullReferenceException.

A quick look in the reflector shows that the filtering is done in .Net code after the windows api has reported the file system change.

I'd therefore suggest that the approach of registering multiple watchers is inefficient as you're putting more load on the API causing multiple callbacks and only one of the filters will match. Much better to just register a single watcher and filter the results yourself.

jdhurst

You could also filter by using FileInfo by comparing to the string of the extension you're looking for.

For example the handler for a file changed event could look like:

void File_Changed(object sender, FileSystemEventArgs e)
{
    FileInfo f = new FileInfo(e.FullPath);

    if (f.Extension.Equals(".jpg") || f.Extension.Equals(".png"))
    {
       //Logic to do whatever it is you're trying to do goes here               
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!