I recently bumped into a weird functionality from Microsoft:
Let's assume our folder c:\tmp123
contains 3 files -1.txt
2.txtx
3.txtxt
a) Invocation of Directory.GetFiles(@"C:\tmp123", "*.txt")
yields in 3 returned items.
b) Invocation of Directory.GetFiles(@"C:\tmp123", "*.txtx")
yields in 1 returned items.
According to Microsoft this is the expected behavior (see Note in MSDN).
My questions are:
Why did Microsoft decide to have such a strange functionality?
How can I overcome this problem?
i.e. how do I have a Search Pattern that would return *.txt
extension only and not return *.txtx
, *.txtstarngefunctionality
, etc.?
Solution 1. You can't. GetFiles method only accepts one option in the overload. Either run it twice with a different extension, or, run it without the filter and afterward filter the result in a loop.
GetFiles(String, String, SearchOption) Returns the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.
The reason for this is backwards compatibility.
Windows was initially built as a graphical interface on top of MSDOS which only had files with 8 characters for the name and a maximum of 3 for the extension. Extentions to the MSDOS file systems allowed Windows to have longer file names and extensions but these would still show up as 8.3 file names in MSDOS.
Since the command prompt on Windows is an evolution of the old command interpreter in MSDOS this means some "anachronistic" behaviours (like the 3 letter search pattern) were kept so applications and scripts built in the "old days" or by "old timers" wouldn't break.
(another example is the fact most windows file systems are case insensitive, yes, you guessed, because the MSDOS one didn't have casing)
If you want a workaround, you could simply retrieve all the file paths
var files = Directory.GetFiles(@"C:\tmp123");
and then filter them by extension as needed
var txtFiles = files.Where(f => f.EndsWith(".txt"));
var txtxFiles = files.Where(f => f.EndsWith(".txtx"));
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