Exclude Results from Directory.GetFiles

If I want to call Directory.GetFiles and return all the files matching the *.bin pattern, but I want to exclude all the files that will match the LOG#.bin pattern LOG#.bin , where # is the current counter of indefinite length. Is there a way to filter the results during the transition to the search filter on GetFiles or do I need to get an array of results and then delete the elements that I want to exclude?

+4
source share
2 answers

You can use Linq, Directory.EnumerateFiles() and the Where() filter - this way you get only the files you need, the rest is filtered out.

Something like this should work:

 Regex re = new Regex(@"^LOG\d+.bin$"); var logFiles = Directory.EnumerateFiles(somePath, "*.bin") .Where(f => !re.IsMatch(Path.GetFileName(f))) .ToList(); 

As stated, Directory.EnumerateFiles requires .NET 4.0. In addition, a slightly cleaner solution (at the cost of slightly more overhead) uses DirectoryInfo / EnumerateFiles() , which returns IEnumerable<FileInfo> , so you have direct access to the file name and extension without further analysis.

+8
source

There is a solution using Linq:

 using System; using System.IO; using System.Linq; namespace getfilesFilter { class Program { static void Main(string[] args) { var files = Directory.GetFiles(@"C:\temp", "*.bin").Select(p => Path.GetFileName(p)).Where(p => p.StartsWith("LOG")); foreach (var file in files) { Console.WriteLine(file); } Console.ReadLine(); } } } 
+2
source

Source: https://habr.com/ru/post/1394325/


All Articles