Say I have "a.txt", "ab.txt", "c.txt" files inside C:\temp\someFolder.
I want to get all.txt files and filter "ab.txt" from results, but do it via SearchPattern only.
I would like to be able to do something like
Directory.GetFiles("C:\\temp", "*.txt -ab", System.IO.SearchOption.AllDirectories)
as opposed to do the filtering outside the GetFiles
function.
Is there a way?
The searchPattern
syntax is very restricted :
The search string to match against the names of files in
path
. This parameter can contain a combination of valid literal path and wildcard (* and?) characters, but it doesn't support regular expressions.
Wildcards allow to match multiple files with a given format, but don't allow exclusion, thus this is not possible.
You will have to rely either on filtering the result of GetFiles
, or use EnumerateFiles
with a filter expression, similar to this answer :
Directory.EnumerateFiles("c:\\temp", "*.txt", SearchOption.AllDirectories)
.Where(f => Path.GetFileName(f) != "ab.txt")
.ToArray();
Note that this approach calls the same internal function InternalEnumeratePaths
in the Directory
class (see here and here ), thus it should not have any performance penalty; to the contrary, it should perform even better, due to calling ToArray
after the collection has been filtered. This is especially true if a large amount of files match the initial searchPattern
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.