Recurse through directory and subdirectories

micropathic

Well-known member
Joined
Oct 23, 2003
Messages
75
Hi,

I need to figure out how to get a list of all of the contents (fiiles and folders) of a given directory including whats in its subdirectories. I plan on populating a listbox with this info. Ive searched the forum for some type of solution, but it seems most of what I had found had to do with using a recursive function to populate a treeview and I cant really figure out how to use that code the way I need it. So, any help would be super appreciated!

Thanks for any help!
 
Hello micropathic,

I put this example together really quickly to kind of show you how to recursively search a directory or drive. Im just adding this data to a richtextbox, but I think youll get the idea.

PHP:
Dim mainDir As String = "D:\"
Dim mainDirStr As String
Dim f As String

    If Directory.Exists(mainDir) Then
      For Each mainDirStr In Directory.GetDirectories("D:\")
            Me.RichTextBox1.Text = Me.RichTextBox1.Text & mainDirStr & vbCrLf
         For Each f In Directory.GetFiles(mainDirStr)
      Me.RichTextBox1.Text = Me.RichTextBox1.Text & f & vbCrLf
    Next
  Next
End If
 
Oops... I just noticed that this code only recurses through 1 level of subdirecories (it doesnt get the subdirectories of the subdirectories). Ive been playing around with the code a little bit more, but cannot seem to get it work. Do you know of anything I can do? Thanks!
 
Recursive function

Watch out for recursiv function as they quickly overload the stack.
Because a function doesnt get removed from the stack as long as its not finish... if you recall to much its gotta give an error. (Stack overflow I think)

Code:
Private Sub GetDirectories(string str )
Begin
Dim mainDir = str
 
if( Directory.GetDirectories( str ).Length > 0 ) Then
 
[font=Courier New][color=black]If Directory.Exists(mainDir) Then 
	  For Each mainDirStr In Directory.GetDirectories("mainDir[/color][/font][font=Courier New][color=#dd0000][color=black]") 
			Me.RichTextBox1.Text = Me.RichTextBox1.Text & mainDirStr & vbCrLf [/color][/color][/font]
[font=Courier New][color=#dd0000][color=black]		   GetDirectories( mainDirStr )
		 For Each f In Directory.GetFiles(mainDir) 
	  Me.RichTextBox1.Text = Me.RichTextBox1.Text & f & vbCrLf 
	  Next[/color][/color][/font]
 
[font=Courier New]End If[/font]
 
[font=Courier New][color=#dd0000][color=#000000]End Sub[/color] [/color][/font]

Didnt test it. So it may have bugs. Be sure not to fall in an infinite loop.

N.B. : We learn at school that its better NOT to use recursive and they are only needed in very few case. THIS case is one of them.

Stay Zen.

This kind of programming is sorted as advance and should be used wisely.
 
Back
Top