如何使用Directory.EnumerateFiles排除隐藏文件和系统文件 [英] How to use Directory.EnumerateFiles excluding hidden and system files
问题描述
我正在枚举目录中的所有文件,以便以后可以处理它们.我想排除隐藏文件和系统文件.
I'm enumerating all files in a directory so that I can process them later. I want to exclude hidden and system files.
这是我到目前为止所拥有的:
This is what I have so far:
IEnumerable<IGrouping<string, string>> files;
files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
.Where(f => (new FileInfo(f).Attributes & FileAttributes.Hidden & FileAttributes.System) == 0)
.GroupBy(Path.GetDirectoryName);
但是,如果我查看结果,我仍然会隐藏起来并且包括系统文件:
However if I look at the results I am still getting hidden and system files included:
foreach (var folder in files)
{
foreach (var file in folder)
{
// value for file here still shows hidden/system file paths
}
}
我发现了此问题与杰罗姆(Jerome)类似,但我什至无法编译它.
I found this question which has a similar example from Jerome but I couldn't even get that to compile.
我在做什么错了?
推荐答案
.Where(f => (new FileInfo(f).Attributes & FileAttributes.Hidden & FileAttributes.System) == 0)
由于 FileAttributes
值是标志,它们在位级别上是分离的,因此您可以适当地将它们组合在一起.因此,FileAttributes.Hidden & FileAttributes.System
将始终为0
.因此,您实质上是在检查以下内容:
Since FileAttributes
values are flags, they are disjunctive on the bit level, so you can combine them properly. As such, FileAttributes.Hidden & FileAttributes.System
will always be 0
. So you’re essentially checking for the following:
(new FileInfo(f).Attributes & 0) == 0
这将永远是正确的,因为您要删除& 0
部分中的任何值.
And that will always be true since you are removing any value with the & 0
part.
您要检查的是文件中是否没有这些标志,或者换句话说,如果没有共同的标志并结合使用这两种标志:
What you want to check is whether the file has neither of those flags, or in other words, if there are no common flags with the combination of both:
.Where(f => (new FileInfo(f).Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0)
您还可以使用 Enum.HasFlag
使其更容易理解:
You can also use Enum.HasFlag
to make this a bit better understandable:
.Where(f => !new FileInfo(f).Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System))
这篇关于如何使用Directory.EnumerateFiles排除隐藏文件和系统文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!