user2282583
user2282583

Reputation: 51

Directory.GetFiles(path, ".txt", SearchOption.AllDirectories); doesn't deliver a file

How would I search all the files in directory and all its sub directories for a specific extension

Directory.GetFiles(path, ".txt", SearchOption.AllDirectories);

The code above returns no files

Upvotes: 1

Views: 10625

Answers (5)

Ogglas
Ogglas

Reputation: 70184

As @tigran and others says you need to use wild card notation. However the difference between .NET Framework and .NET should be mentioned. See table below.

.NET Framework only: When you use the asterisk wildcard character in searchPattern and you specify a three-character file extension, for example, ".txt", this method also returns files with extensions that begin with the specified extension. For example, the search pattern ".xls" returns both "book.xls" and "book.xlsx". This behavior only occurs if an asterisk is used in the search pattern and the file extension provided is exactly three characters. If you use the question mark wildcard character somewhere in the search pattern, this method returns only files that match the specified file extension exactly. The following table depicts this anomaly in .NET Framework.

Files in directory Search pattern .NET 5+ returns .NET Framework returns
file.ai, file.aif *.ai file.ai file.ai
book.xls, book.xlsx *.xls book.xls book.xls, book.xlsx
ello.txt, hello.txt, hello.txtt ?ello.txt ello.txt, hello.txt ello.txt, hello.txt

In .NET Framework you can use this code to filter the results:

Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Where(filePath => filePath.EndsWith(".txt"));

Source:

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=net-8.0#system-io-directory-getfiles(system-string-system-string)

Upvotes: 0

Bearcat9425
Bearcat9425

Reputation: 1608

I believe its your search pattern or second parameter. should be "*.txt".

Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Upvotes: 6

Jan
Jan

Reputation: 2168

The filter needs to be "*.txt":

Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Upvotes: 2

Tigran
Tigran

Reputation: 62265

you need to use wild card notation

Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

in your case you're searching for files ".txt" name, instead you need tell to API to retrieve to you all files that has txt extension.

Upvotes: 9

tnw
tnw

Reputation: 13887

Because you're searching literally for the file named .txt

Use a wildcard character like so: *.txt and it should pull up any .txt files.

See documentation: http://msdn.microsoft.com/en-us/library/ms143316.aspx

Upvotes: 7

Related Questions