Question

I wish to get a list of all the files of a certain extension (recursive), but only the files ending with that extension.

For example, I wish to get all the files with the ".exe" extension, If I have the following files:

file1.exe , file2.txt.exe , file3.exe.txt , file4.txt.exe1 , file5.txt

I expect to get a list of 1 file, which is: file1.exe.

I'm trying to use the following line:

List<string> theList = Directory.GetFiles(@"C:\SearchDir", "*.exe", SearchOption.AllDirectories).ToList();

But what I get is a list of the following three files: file1.exe , file2.txt.exe , file4.txt.exe1

Any ideas?

Was it helpful?

Solution 2

Try this:

var exeFiles = Directory.EnumerateFiles(sourceDirectory, 
                                        "*", SearchOption.AllDirectories)
               .Where(s => s.EndsWith(".exe") && s.Count( c => c == '.') == 2)
               .ToList();

OTHER TIPS

This is a common issue to see. Take note to the MSDN documentation:

When using the asterisk wildcard character in a searchPattern, such as "*.txt", the matching behavior when the extension is exactly three characters long is different than when the extension is more or less than three characters long. A searchPattern with a file extension 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.

You can't solve it by searching for the .exe extension; you'll need to filter your results one more time in the client code.

Now, one thing to note also is this. The following examples would in fact be considered executable files:

file1.exe
file2.txt.exe

whereas this one wouldn't technically be considered an executable file.

file4.txt.exe1

So the question then becomes, what algorithm do you want? It appears to me you want the following:

  • Files that have an extension of exe.
  • Files that don't have multiple extensions.

Have a look at Ahmed's answer for a fantastic approach to getting the algorithm you want.

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