I need to decide whether file name fits to file mask. The file mask could contain * or ? characters. Is there any simple solution for this?
bool bFits = Fits("myfile.txt", "my*.txt"); private bool Fits(string sFileName, string sFileMask) { ??? anything simple here ??? }
I appreciate finding Joel's answer--saved me some time as well ! I did, however, have to make a few changes to make the method do what most users would expect:
private bool FitsMask(string fileName, string fileMask) { Regex mask = new Regex( '^' + fileMask .Replace(".", "[.]") .Replace("*", ".*") .Replace("?", ".") + '$', RegexOptions.IgnoreCase); return mask.IsMatch(fileName); }
For even more flexibility, here is a plug-compatible method built on top of the original. This version lets you pass multiple masks (hence the plural on the second parameter name fileMasks) separated by lines, commas, vertical bars, or spaces. I wanted it so that I could let the user put as many choices as desired in a ListBox and then select all files matching any of them. Note that some controls (like a ListBox) use CR-LF for line breaks while others (e.g. RichTextBox) use just LF--that is why both "\r\n" and "\n" show up in the Split list.
private bool FitsOneOfMultipleMasks(string fileName, string fileMasks) { return fileMasks .Split(new string[] {"\r\n", "\n", ",", "|", " "}, StringSplitOptions.RemoveEmptyEntries) .Any(fileMask => FitsMask(fileName, fileMask)); }
The earlier version of FitsMask (which I have left in for comparison) does a fair job but since we are treating it as a regular expression it will throw an exception if it is not a valid regular expression when it comes in. The solution is that we actually want any regex metacharacters in the input fileMask to be considered literals, not metacharacters. But we still need to treat period, asterisk, and question mark specially. So this improved version of FitsMask safely moves these three characters out of the way, transforms all remaining metacharacters into literals, then puts the three interesting characters back, in their "regex'ed" form.
One other minor improvement is to allow for case-independence, per standard Windows behavior.
private bool FitsMask(string fileName, string fileMask) { string pattern = '^' + Regex.Escape(fileMask.Replace(".", "__DOT__") .Replace("*", "__STAR__") .Replace("?", "__QM__")) .Replace("__DOT__", "[.]") .Replace("__STAR__", ".*") .Replace("__QM__", ".") + '$'; return new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(fileName); }
I have been remiss in not updating this earlier but these references will likely be of interest to readers who have made it to this point:
Try this:
private bool FitsMask(string sFileName, string sFileMask) { Regex mask = new Regex(sFileMask.Replace(".", "[.]").Replace("*", ".*").Replace("?", ".")); return mask.IsMatch(sFileName); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With