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?
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.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With