Directory.GetFiles and extensions longer than 3 characters

This question pops up in various forums every once in a while. Essentially, someone would call Directory.GetFiles with something like “*.dat” and would be annoyed to find that *.dat matches .dat, .data, and even .date. Not what they wanted.

Unfortunately, this is by design. You have to do post-filtering to select just the files you want.

var files =  Directory.GetFiles(@"d:\tmp", "*.dat").Where(
    s => s.EndsWith(".dat"));

The reason it works this way is most likely for backward compatibility with the old 8.3 file system. And it’s really not a .NET restriction here, it’s an API restriction. Both FindFirstFile and FindNextFile have this behavior and it’s these API calls that are P/Invoked by Directory.GetFiles.