SearchPattern Configuration in EnumerateFiles

I have a directory with 2 files:

  • file1.xls
  • file2.xlsx

If I do this:

directoryInfo.EnumerateFiles("*.xls", SearchOption.TopDirectoryOnly) 

It returns both files, and I only need the first one (file1.xls). How can i do this?

Thanks!

+6
source share
5 answers

It looks like the DirectoryInfo class is using the Win32 FindFirstFile call under the hood.

This allows only wildcards:

* to match any character

? to match 0 or more characters - see comments .

Therefore, you will have to filter the results yourself, possibly using the following:

 directoryInfo.EnumerateFiles("*.xls", SearchOption.TopDirectoryOnly) .Where(fi => fi.Extension == ".xls"); 
+9
source

This is really the expected behavior. It is strange, but it is documented.

On MSDN, we can read the note:

When using an asterisk wildcard character in searchPattern, such as "* .txt", the matching behavior when the extension is exactly three characters is different from when the extension is more or less than three characters. SearchPattern with a file extension of exactly three characters returns files with an extension of three or more characters, where the first three characters correspond to the file extension specified in searchPattern. SearchPattern with a file extension of one, two or more than three characters returns only files with extensions of exactly the same length that match the file extension specified in searchPattern. When using a wildcard character, this method returns only files matching the specified file extension. For example, in two files "file1.txt" and "file1.txtother" in the directory, the search pattern "file? .Txt" returns only the first file, and the search pattern "file * .txt" returns both files.

+3
source

you can use the extension methods IEnumerable.First() , IEnumerable.FirstOrDefault() , or if the template is important, return the search template for listing.

0
source

Something like that:

 directoryInfo.EnumerateFiles(".xls",SearchOption.TopDirectoryOnly) .Where( f => Path.GetExtension( f ) == ".xls" ); 
0
source

This works using .Except () and should be faster:

  var dir = new DirectoryInfo(myFolderPath); ICollection<FileInfo> files = dir.EnumerateFiles("*.xls").Except(dir.EnumerateFiles("*.xls?")).ToList(); 

You can use Union (s) to add additional extensions. It is cleaner (I believe it is faster, although not tested) in general. IMO

0
source

Source: https://habr.com/ru/post/916981/


All Articles