Get files in a directory

sarthemaker

Active member
Joined
Sep 4, 2009
Messages
36
Programming Experience
5-10
I am trying to get the files in a directory and display them in a list box. I have that part working, but I would only like to show the files that are NOT hidden. I am currently using this:

VB.NET:
Dim atts As FileAttribute = CheckDirectory.Attributes 
If (atts And FileAttribute.Hidden) = FileAttribute.Hidden Then...

this is part of a for each loop.

But is there a way to only return the files that are not hidden, instead of having to check if they are?

I also need this to see how many files are in each directory so I don't have to count each file in each directory within the current folder. If I use the CheckDirectory.GetFiles().count, it counts the hidden files to.. A for each loop is just too slow..

does any one know of a way that I can accomplish this?
 
Thread Moved

What I would do to get the files is:
VB.NET:
Dim fi As New FileInfo(File from Loop here)
If Not (fi.Attributes And FileAttribute.Hidden) = FileAttribute.Hidden Then AddToList
fi = Nothing
'Continue loop
I can't think of an easier way of doing this.
 
Assuming you're using .NET 3.5 then you have LINQ at your disposal, which is ideal for filtering lists like this. You have no option but to retrieve all files in the first place but filtering that list is easier with LINQ:
VB.NET:
Me.ListBox1.DisplayMember = "Name"
Me.ListBox1.ValueMember = "FullName"
Me.ListBox1.DataSource = (From file In New IO.DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments).GetFiles() _
                          Where (file.Attributes And IO.FileAttributes.Hidden) <> IO.FileAttributes.Hidden).ToArray()
If you want to expand that last line out for clarity:
VB.NET:
Dim folder As New IO.DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
Dim allFiles As IO.FileInfo() = folder.GetFiles()
Dim nonHiddenFiles = From file In allFiles _
                     Where (file.Attributes And IO.FileAttributes.Hidden) <> IO.FileAttributes.Hidden

Me.ListBox1.DataSource = nonHiddenFiles.ToArray()
 
Back
Top