[英]Exclude results from Directory.GetFiles
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. 如果我想调用Directory.GetFiles并让它返回与模式*.bin
匹配的所有文件,但我想排除所有与模式LOG#.bin
匹配的文件,其中#
是不确定长度的运行计数器。 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? 有没有办法在将搜索过滤器传递给GetFiles
的步骤中过滤掉结果,或者我必须获取结果数组然后删除我要排除的项目?
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. 您可以使用Linq, Directory.EnumerateFiles()
和Where()
过滤器 - 这样您只会得到所需的文件,其余的将被过滤掉。
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. 正如指出Directory.EnumerateFiles
需要.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. 另外一个更清晰的解决方案(以更多的开销为代价)使用DirectoryInfo
/ EnumerateFiles()
返回IEnumerable<FileInfo>
这样您就可以直接访问文件名和扩展名而无需进一步解析。
There is a solution using Linq: 使用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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.