Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration SearchPattern in EnumerateFiles

I have a directory with 2 files:

  • file1.xls
  • file2.xlsx

If I do:

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

It is returning both files, and I only want the first (file1.xls). How can I do this?

Thank you!

like image 636
Pedre Avatar asked May 30 '12 07:05

Pedre


People also ask

What is directory EnumerateFiles?

EnumerateFiles(String, String, EnumerationOptions) Returns an enumerable collection of full file names that match a search pattern and enumeration options in a specified path, and optionally searches subdirectories. EnumerateFiles(String) Returns an enumerable collection of full file names in a specified path.

How do I enumerate files and folders?

To enumerate directories and files, use methods that return an enumerable collection of directory or file names, or their DirectoryInfo, FileInfo, or FileSystemInfo objects. If you want to search and return only the names of directories or files, use the enumeration methods of the Directory class.


2 Answers

It looks like under the hood, the DirectoryInfo class uses the Win32 call FindFirstFile.

This only allows the wildcards:

* to match any character

? to match 0 or more characters - see comments.

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

directoryInfo.EnumerateFiles("*.xls", SearchOption.TopDirectoryOnly)
             .Where(fi => fi.Extension == ".xls");
like image 136
g t Avatar answered Nov 14 '22 08:11

g t


This is actually an expected behaviour. It's odd, but it is documented.

On MSDN we can read a remark:

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. A searchPattern with a file extension of one, two, or more than three characters returns only files having extensions of exactly that length that match the file extension specified in the searchPattern. When using the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files, "file1.txt" and "file1.txtother", in a directory, a search pattern of "file?.txt" returns just the first file, while a search pattern of "file*.txt" returns both files.

like image 3
Piotr Zierhoffer Avatar answered Nov 14 '22 10:11

Piotr Zierhoffer