How can I make GetFiles() exclude files with extensions that start with the search extension?

topofsteel picture topofsteel · Nov 27, 2013 · Viewed 14.8k times · Source

I am using the following line to return specific files...

FileInfo file in nodeDirInfo.GetFiles("*.sbs", option)

But there are other files in the directory with the extension .sbsar, and it is getting them, too. How can I differentiate between .sbs and .sbsar in the search pattern?

Answer

Daniel Peñalba picture Daniel Peñalba · Nov 27, 2013

The issue you're experiencing is a limitation of the search pattern, in the Win32 API.

A searchPattern with a file extension (for example *.txt) of exactly three characters returns files having an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern.

My solution is to manually filter the results, using Linq:

nodeDirInfo.GetFiles("*.sbs", option).Where(s => s.EndsWith(".sbs"),
    StringComparison.InvariantCultureIgnoreCase));