tags:

views:

263

answers:

2

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
From what I understand c# 4.0 should make this much faster and easier ;-)
Dested
You can do this in a single line, without the SELECT **var files = new DirectoryInfo(@"C:\").GetFiles().Where(x => (x.Attributes **
astander
Or even just use the directory class (reduces @astanders solution by 8 characters)var files = Directory.GetFiles( @"c:\").Where(x=>(x.Attributes
BioBuckyBall
@Dested - I'm using C# 4.0, how does that make this faster and easier??
James Cadd
`Directory.GetFiles` returns a string array so your code golf solution doesn't quite work.
Austin Salonen
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
+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