Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude results from Directory.GetFiles

Tags:

c#

.net

If I want to call Directory.GetFiles and have it return all files that match the pattern *.bin but I want to exclude all of the files that would match the pattern LOG#.bin where # is a running counter of indeterminate length. Is there a way to filter out the results at the step of passing in a search filter to GetFiles or must I get the result array then remove the items that I want to exclude?

like image 497
Scott Chamberlain Avatar asked Dec 21 '22 02:12

Scott Chamberlain


2 Answers

You can use Linq, Directory.EnumerateFiles() and a Where() filter - that way you only end up with the files you want, 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 pointed out Directory.EnumerateFiles requires .NET 4.0. Also a somewhat cleaner solution (at the cost of a little more overhead) is using DirectoryInfo / EnumerateFiles() which returns an IEnumerable<FileInfo> so you have direct access to the file name and the extension without further parsing.

like image 144
BrokenGlass Avatar answered Jan 03 '23 22:01

BrokenGlass


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();
        }
    }
}
like image 45
Gustavo F Avatar answered Jan 03 '23 22:01

Gustavo F