Directory.GetFiles() returns all files, even those that are marked as hidden. Is there a way to get a list of files that excludes hidden files?
+7
A:
This should work for you:
DirectoryInfo directory = new DirectoryInfo(@"C:\temp");
FileInfo[] files = directory.GetFiles();
var filtered = files.Select(f => f)
.Where(f => (f.Attributes & FileAttributes.Hidden) == 0);
foreach (var f in filtered)
{
Debug.WriteLine(f);
}
Austin Salonen
2010-03-10 15:54:07
From what I understand c# 4.0 should make this much faster and easier ;-)
Dested
2010-03-10 15:55:40
You can do this in a single line, without the SELECT **var files = new DirectoryInfo(@"C:\").GetFiles().Where(x => (x.Attributes **
astander
2010-03-10 16:00:17
Or even just use the directory class (reduces @astanders solution by 8 characters)var files = Directory.GetFiles( @"c:\").Where(x=>(x.Attributes
BioBuckyBall
2010-03-10 16:24:07
@Dested - I'm using C# 4.0, how does that make this faster and easier??
James Cadd
2010-03-10 16:57:58
`Directory.GetFiles` returns a string array so your code golf solution doesn't quite work.
Austin Salonen
2010-03-10 17:00:11
Indeed the `Select` is unnecessary. As for the rest, I was trying to show off the other data types in case the OP was unaware of them.
Austin Salonen
2010-03-10 17:03:08
+2
A:
Using .NET 4.0 and Directory.EnumerateDirectories, you could use this construct :
var hiddenFilesQuery = from file in Directory.EnumerateDirectories(@"c:\temp")
let info = new FileInfo(file)
where (info.Attributes & FileAttributes.Hidden) == 0
select file;
This is basically the same as the other answer, except Directory.EnumerateDirectories is a bit more lazy. This is not very useful if you enumerate everything, though.
(The let is here to have the query a but more readeable).
Jerome Laban
2010-03-10 18:00:04