3

I need to get all .txt files in all subfolders of a specified folder so I do:

var files = Directory.GetFiles(reportsFolder, "*.txt", SearchOption.AllDirectories);

However, in some folders I also have files with extensions like .txt_TODO, and these are also being retrieved by GetFiles.

How can I skip these files?

Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
Ivan-Mark Debono
  • 13,730
  • 22
  • 106
  • 224

1 Answers1

0

Just filter the result by comparing the extension to ".txt", e.g. using LINQ:

var files = Directory.GetFiles(reportsFolder, "*.txt", SearchOption.AllDirectories)
    .Where(f => Path.GetExtension(f).Equals(".txt", StringComparison.OrdinalIgnoreCase))
    .ToArray();
Klaus Gütter
  • 8,166
  • 5
  • 28
  • 33
  • `.EnumerateFiles` instead of `.GetFiles` will be better choice (no premature materialization) in the context – Dmitry Bychenko Feb 08 '19 at 09:09
  • @DmitryBychenko: Sure; but then also the ToArray() has to be removed... What's better depends on what he is doing with the returned collection. – Klaus Gütter Feb 08 '19 at 09:11
  • @KlausGütter: Even with final `.ToArray()` switching to `EnumerateFiles` seems to be a better option: the materialized result of `Directory.GetFiles` is immediately lazily enumerated by `Where`, so replacing it with `EnumerateFiles` doesn't change the behaviour if the final `.ToArray()` is left intact. – Vlad Feb 08 '19 at 12:43