Getting subdirectories

Audax321

Well-known member
Joined
May 4, 2002
Messages
90
Okay I have my program finding subdirectories like this:

Code:
Dim subdir as string()
Dim addsub as string
Dim targetdirectory

subdir = system.io.directory.getdirectories(targetdirectory)

For each addsub in subdir
     lstdir.items.add(addsub)
Next addsub

The problem with this code is that it only retrieves subdirectoris one level deep. Is there any way to retrieve all subdirectories. For example... enter C:\MP3 for target directory returns:

C:\MP3
C:\MP3\MP3CD1
C:\MP3\MP3CD1\GoodMP3s
C:\MP3\MP3CD1\GoodMP3s\MaybeTheseMP3sAreJunk

and so on and so on...

basically goes as deep as possible to retrieve all subdirectories in the main directory that was initially selected... Thanks... :)

And still, if someone could explain file input and output in VB.NET, I would really appreciate it... its confusing..
 
I dont do NET yet, but I imagine you would have to change your local directory to a subdirectory in order to get the subdirectories of that subdirectory....

I wrote an example in Tutors Corner on recursively searching directories, although the looping (non-recursive) version is probably better.
 
Thats the same thing I was thinking, but how would you tell the loop to stop. Because different directories can have different numbers of subdirectories... So wouldnt it keep looping and looping trying to find more subdirectories...?
 
What I did was....

Have an array of strings. Every time I find a subdirectory, I add it to the array. After I finish the current directory, I pull the next one off the array, set the current directory to it, and repeat the process. The loop finishes when I get to the end of the array, and the array is the entire list of directories.
 
I hope this code will help someone else:

It just loops through the subdirectories as BillSoo said above..
Im just pasting all of the code from my form...

Code:
Dim strSubDir As String()
    Dim strSub As String
    Dim inti As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        lstseldir.Items.Add("C:\MP3s")
        inti = 0

        Do While inti <= lstseldir.Items.Count - 1
            If (System.IO.Directory.Exists(lstseldir.Items.Item(inti)) = True) Then
                strSubDir = System.IO.Directory.GetDirectories(lstseldir.Items.Item(inti))

                For Each strSub In strSubDir
                    If (strSub <> "") Then
                        lstseldir.Items.Add(strSub)
                    End If
                Next strSub
            End If

            inti = inti + 1
        Loop
    End Sub
 
Back
Top