Question

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?

Was it helpful?

Solution 2

Try this, filtered using file extension.

  FileInfo[] files = nodeDirInfo.GetFiles("*", SearchOption.TopDirectoryOnly).
            Where(f=>f.Extension==".sbs").ToArray<FileInfo>();

OTHER TIPS

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));

That's the behaviour of the Win32 API (FindFirstFile) that is underneath GetFiles() being reflected on to you.

You'll need to do your own filtering if you must use GetFiles(). For instance:

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

Or more efficiently:

EnumerateFiles("*", searchOption).Where(s => s.EndsWith(".sbs", 
    StringComparison.InvariantCultureIgnoreCase));

Note that I use StringComparison.InvariantCultureIgnoreCase to deal with the fact that Windows file names are case-insensitive.

If performance is an issue, that is if the search has to process directories with large numbers of files, then it is more efficient to perform the filtering twice: once in the call to GetFiles or EnumerateFiles, and once to clean up the unwanted file names. For example:

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

Its mentioned in docs

When using the asterisk wildcard character in a searchPattern,a searchPattern with a file extension of exactly three characters returns files having an extension of three or more characters.When using the question mark wildcard character, this method returns only files that match the specified file extension.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top