1

I need to get all ASP files in a folder, so I wrote a code like this:

string[] files = Directory.GetFiles(@"C:\Folder", "*.asp", SearchOption.AllDirectories);

However, it also returns files with extension "aspx".

Is there a way to specify the end of the extension?

Sorry for my english and thanks in advance.

Rafael Araujo
  • 13
  • 1
  • 4
  • didn't test it, but maybe the pattern `*.asp?` will work – Viper Sep 26 '14 at 18:16
  • You can try IF THEN ELSE statement. IF var == "*.asp". So first write a function that checks for equality, and then pass that function as an input parameter. – Juniar Sep 26 '14 at 18:30

2 Answers2

5

Is there a way to specify the end of the extension?

There isn't a way to do this directly. The best option would be to switch to Directory.EnumerateFiles and filter afterwards:

var files = Directory.EnumerateFiles(@"C:\Folder", "*.asp", SearchOption.AllDirectories)
                     .Where(f => f.EndsWith(".asp", StringComparison.OrdinalIgnoreCase));

This is because the Directory methods have specific behavior which prevents this from working directly. From the docs:

If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".

This is an exception to the normal search rules, but, in your case, is working against you. Using EnumerateFiles streams the results, and filtering afterwards allows you to find only the proper matches.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

Unfortunately, i don't think there's a built in way. but

Directory.EnumerateFiles(@"C:\Folder", "*.asp", SearchOption.AllDirectories).Where(f => f.EndsWith(".asp")

should be as performant as a direct query would be. (note that EnumerateFiles returns an IEnumerable and is preferable to GetFiles if you don't need the files actually in an array)

ths
  • 2,858
  • 1
  • 16
  • 21