Equ*_*lsk 6 c# ienumerable fileinfo
我正在枚举目录中的所有文件,以便稍后处理它们.我想排除隐藏和系统文件.
这是我到目前为止:
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);
Run Code Online (Sandbox Code Playgroud)
但是,如果我查看结果,我仍然会隐藏并包含系统文件:
foreach (var folder in files)
{
foreach (var file in folder)
{
// value for file here still shows hidden/system file paths
}
}
Run Code Online (Sandbox Code Playgroud)
我发现这个问题与杰罗姆有类似的例子,但我甚至无法编译.
我究竟做错了什么?
.Where(f => (new FileInfo(f).Attributes & FileAttributes.Hidden & FileAttributes.System) == 0)
Run Code Online (Sandbox Code Playgroud)
由于FileAttributes值是标志,它们在位级别上是分离的,因此您可以正确地组合它们.因此,FileAttributes.Hidden & FileAttributes.System永远都是0.所以你基本上检查以下内容:
(new FileInfo(f).Attributes & 0) == 0
Run Code Online (Sandbox Code Playgroud)
这将永远是真实的,因为您正在删除& 0零件的任何值.
您要检查的是文件是否既没有这些标志,换句话说,如果没有两个组合的公共标志:
.Where(f => (new FileInfo(f).Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0)
Run Code Online (Sandbox Code Playgroud)
你也可以使用它Enum.HasFlag来使这个更容易理解:
.Where(f => !new FileInfo(f).Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2283 次 |
| 最近记录: |