Reputation: 2988
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?
Upvotes: 2
Views: 3316
Reputation: 1864
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));
Upvotes: 8
Reputation: 23093
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...
Upvotes: 2
Reputation: 2362
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.
Upvotes: -1
Reputation: 172378
Try like this:
foreach (DirectoryInfo Dir in Directory.GetDirectories(directorypath))
{
if (!Dir.Attributes.HasFlag(FileAttributes.Hidden))
{
}
}
Upvotes: 2