DirectoryInfo()。GetFileSystemInfos() - 如何避免隐藏文件夹?

时间:2012-11-07 03:33:09

标签: c# filesysteminfo

如果我这样做:

var entries = new DirectoryInfo(@"C:\Folder1")
                   .GetFileSystemInfos("test*", SearchOption.AllDirectories);

当我有这样的文件夹结构时,隐藏“HiddenFolder”但不隐藏“test.txt”文件:

C:\Folder1\
C:\Folder1\HiddenFolder\
C:\Folder1\HiddenFolder\test.txt

那么如何编写代码来获取“test.txt”文件?

(您可能认为GetFileSystemInfos会跳过隐藏文件夹,但事实并非如此。)

这是部分解决方案

此代码删除隐藏文件和文件夹,但不处理隐藏文件夹中的非隐藏文件!

  var includeLocalFolderNames = true; // to include folder names in the list

  var hiddenFolders = new List<FileSystemInfo>();
  return entries
    .Where(entry =>
      {
        // skip if this entry is hidden, or it is in a hidden folder

        var isHidden = (entry.Attributes & FileAttributes.Hidden) != 0;
        if (isHidden)
        {
          hiddenFolders.Add(entry);
          return false;
        }
        return !hiddenFolders.Any(fsi => entry.FullName.StartsWith(fsi.FullName));
      })
    .Where(entry =>
      {
        // include folder names if requested...

        if (includeLocalFolderNames) return true;
        return (entry.Attributes & FileAttributes.Directory) == 0;
      })
    .Select(entry => {
        // do something...
        return entry.Name;
      });

1 个答案:

答案 0 :(得分:1)

当然不是最优和/或最优雅的解决方案。

var root = new DirectoryInfo(path);
var nonHiddenDirectories =
    root.GetDirectories("*", SearchOption.AllDirectories).Where(
        d => (d.Attributes & FileAttributes.Hidden) == 0).ToArray();
var nonHiddenFiles =
    nonHiddenDirectories.SelectMany(d => d.GetFiles()).Where(
        f => (f.Attributes & FileAttributes.Hidden) == 0);