Reputation: 5459
I know that this thread exists, but the answer is not completely correct.
I have a folder and want to get all file names which have an extension .DOC
. But there are also files in the directory with the extension .DOCX
which I don't want in the returned value.
But by using string[] files = System.IO.Directory.GetFiles(path, "*.DOC")
I get both of them while I am searching for only the .DOC
files.
Thus, currently I am reading both and using an if
statement to filter the filenames again:
foreach (var originfile in files)
{
if (Path.GetExtension(originfile).ToUpper() == ".DOC")
{
...
}
}
I wanted to ask if there is any possibility to get only the .DOC
files with System.IO.Directory.GetFiles
. The documentation states that it is not possible to use regular expressions.
Upvotes: 2
Views: 1536
Reputation: 77926
Well you can use a System.Linq
query to get what you want like
var files = System.IO.Directory.GetFiles(path, "*.DOC")
.Select(x => Path.GetExtension(x).ToUpper() == ".DOC")
.ToList();
Upvotes: 0
Reputation: 8573
From the documentation you linked:
When using the asterisk wildcard character in a searchPattern (for example, ".txt"), the matching behavior varies depending on the length of the specified file extension. A searchPattern with a file extension of exactly three characters returns files with 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 with 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 in a directory, "file1.txt" and "file1.txtother", a search pattern of "file?.txt" returns only the first file, while a search pattern of "file.txt" returns both files.
So if you're using the *
wildcard, then it's not possible, and you must do the way you're doing.
Upvotes: 4