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?
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...
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.