How to set filter for FileSystemWatcher for multiple file types?
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);
}
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 = ""; // This matches all filenames
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.");
}
}