0

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?

janw
  • 8,758
  • 11
  • 40
  • 62
Atalia.d
  • 131
  • 1
  • 13

2 Answers2

6

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.

janw
  • 8,758
  • 11
  • 40
  • 62
0

I came to something similar today and, in my case, I needed the full FileInfo object.

I came to this

var path = @"C:\SomeDir\";
var dInfo = new DirectoryInfo(path);
var files = dInfo.GetFiles("*").Where(x => x.Name != "SomeFile.txt").ToArray();

I hope it's useful.