user99874
user99874

Reputation:

System.IO.Directory search pattern not working as expected

I am attempting to retrieve jpeg and jpg files using the following statement:

string[] files = Directory.GetFiles(someDirectoryPath, "*.jp?g");

MSDN's docs for System.IO.Directory.GetFiles(string, string) state that ? represents "Exactly zero or one character.", however the above block selects jpeg files but omits jpg files.

I am currently using the overly-permissive search pattern "*.jp*g" to achieve my results, but it wrinkles my brain because it should work.

Upvotes: 2

Views: 705

Answers (2)

Yahia
Yahia

Reputation: 70379

You could either use "*" as a pattern and process the result yourself OR use

string[] files = Directory.GetFiles(someDirectoryPath, "*.jpg").Union (Directory.GetFiles(someDirectoryPath, "*.jpeg")).ToArray();

According to the Docs the pattern you use would return only files with extensions which are 4 characters long.

MSDN reference on Union

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503469

From the docs you linked to:

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.

I suspect that's the problem. To be honest, I'd probably fetch all the files and then postprocess them in code - it'll make for code which is simpler to reason about than relying on the Windows path-handling oddities.

Upvotes: 4

Related Questions