2

I want to create a list of all the files in a directory, except hidden fies and files inside hidden folder in the directory. 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?

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Sameera Kumarasingha
  • 2,908
  • 3
  • 25
  • 41

4 Answers4

8

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));
Cadburry
  • 1,844
  • 10
  • 21
2

Try like this:

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

    }
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

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...

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
-1

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.

Priyank Sheth
  • 2,352
  • 19
  • 32