LabRat
LabRat

Reputation: 2014

List all file in all sub directorys regardless of how many

I have the following code to try and get all file names in my parent directory and all its sub directories.

The code works, but not how I would like. Namely it will process all files in the parent directory and all in the "first- level" of sub directories but I want to be able to go into all levels of sub directories.

How do I do that?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'ListBox1.Items.AddRange(IO.Directory.GetFiles("C:\"))

    For Each Dir As String In IO.Directory.GetDirectories("C:\Program Files")
        ' ListBox1.Items.Add(Dir)
        ListBox1.Items.AddRange(IO.Directory.GetFiles(Dir))
    Next
End Sub

Upvotes: 0

Views: 2809

Answers (1)

Xavier Peña
Xavier Peña

Reputation: 7909

Here is the code that does what you want in just two lines:

    Dim result As List(Of String) = System.IO.Directory.GetFiles("C:\Program Files", "*", System.IO.SearchOption.AllDirectories)
    listBox1.DataSource = result

[ Credit do @Carsten in this post, which listed subdirectories and I changed to listing files and binded it to the ListBox element. I didn't know that the recursive solution was already implemented in System.IO ]

Edit1: taking comment suggestion.

Edit2: GetFiles does not allow a workaround for this problem: when you attempt to read could be configured so that the current user may not access them. More details (and solution with a recursive function) here.

Upvotes: 2

Related Questions