简体   繁体   English

获取隐藏目录中的文件以外的所有文件?

[英]Get all files except files in hidden directories?

I want to create a list of all the files in a directory, except hidden fies and files inside hidden folder in the directory. 我想创建一个目录中所有文件的列表,除了隐藏的fies和目录中隐藏文件夹内的文件。 I used this method, 我用过这种方法,

new DirectoryInfo(path).GetFiles("*.*", SearchOption.AllDirectories)
                     .Where(f => (f.Attributes & FileAttributes.Hidden) == 0)

But the above method return files inside hidden folders. 但上面的方法返回隐藏文件夹中的文件。 Are there any other way to do this without recursively iterating through directories? 有没有其他方法可以做到这一点,而无需递归迭代目录?

Thats because the Files in the hidden-subfolders aren't hidden. 那是因为隐藏子文件夹中的文件没有被隐藏。 To Check this you have to walk recursively to each folder & check the Folder-Attributes too. 要检查这一点,你必须递归地走到每个文件夹并检查文件夹属性。

Example function: 功能示例:

   private static IList<FileInfo> getNonHidden(DirectoryInfo baseDirectory)
    {
        var fileInfos = new List<System.IO.FileInfo>();
        fileInfos.AddRange(baseDirectory.GetFiles("*.*", SearchOption.TopDirectoryOnly).Where(w => (w.Attributes & FileAttributes.Hidden) == 0));
        foreach (var directory in baseDirectory.GetDirectories("*.*", SearchOption.TopDirectoryOnly).Where(w => (w.Attributes & FileAttributes.Hidden) == 0))
            fileInfos.AddRange(getNonHiddenFiles(directory));

        return fileInfos;
    }

How to use: 如何使用:

  var path = @"c:\temp\123";
  var result = getNonHidden(new DirectoryInfo(path));

Try like this: 试试这样:

foreach (DirectoryInfo Dir in Directory.GetDirectories(directorypath))
{
    if (!Dir.Attributes.HasFlag(FileAttributes.Hidden))
    {

    }
}

One way without "manually iterating" would be the following: 没有“手动迭代”的一种方法如下:

var dirInfo = new DirectoryInfo(path);
var hiddenFolders = dirInfo.GetDirectories("*", SearchOption.AllDirectories)
    .Where(d => (d.Attributes & FileAttributes.Hidden) != 0)
    .Select(d => d.FullName);

var files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories)
    .Where(f => (f.Attributes & FileAttributes.Hidden) == 0 && 
        !hiddenFolders.Any(d => f.FullName.StartsWith(d)));

BUT this will be iterating the whole directory tree twice and has the .Any -overhead for every file => use @Catburry's solution as it has a better performance and is easier to maintain IMO... 但是这将是遍历整个目录树的两倍,并已在.Any -overhead每个文件=>使用@ Catburry的解决方案,因为它有一个更好的性能和更容易维护IMO ...

Can you try below code: 你能尝试下面的代码:

var x = new DirectoryInfo(@"D://Priyank Sheth/Projects/").GetFiles("*.*", SearchOption.AllDirectories)
                     .Where(f => (f.Directory.Attributes & FileAttributes.Hidden) == 0 && (f.Attributes & FileAttributes.Hidden) == 0);

I have not tried it but let me know if it does not work. 我没有尝试过,但如果它不起作用,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM