excaliber
04-03-2004, 02:42 PM
Thought I'd share this snippet of code. It recursively goes through every subdirectory under the main directory, listing both subdir's and files.
It's overloaded. Call the first one by providing only the target path. It uses the second overloaded function for the recursive part. The code is fairly self-explanatory.
Private Overloads Function Recursive(ByVal strPath As String)
Dim oDir As New System.IO.DirectoryInfo(strPath)
Dim oSubDir() As System.IO.DirectoryInfo
Dim oFiles() As System.IO.FileInfo
Dim i As Int32
oFiles = oDir.GetFiles
For i = 0 To oFiles.Length - 1
Debug.WriteLine(oFiles(i).Name.ToString)
Next
oSubDir = oDir.GetDirectories()
For i = 0 To oSubDir.Length - 1
Debug.WriteLine(oSubDir(i).Name.ToString)
'more code to do whatever here
Call Recursive(oSubDir(i), 1)
Next
End Function
Private Overloads Function Recursive(ByVal oDir As System.IO.DirectoryInfo, ByVal intLevel As Int32)
Dim oSubDir() As System.IO.DirectoryInfo
Dim oFiles() As System.IO.FileInfo
Dim i As Int32
oFiles = oDir.GetFiles
For i = 0 To oFiles.Length - 1
Debug.WriteLine(New String(" ", intLevel) & ">" & oFiles(i).Name.ToString)
Next
oSubDir = oDir.GetDirectories()
For i = 0 To oSubDir.Length - 1
Debug.WriteLine(New String(" ", intLevel) & oSubDir(i).Name.ToString)
'more code to do whatever here
Call Recursive(oSubDir(i), intLevel + 1)
Next
End Function
It's overloaded. Call the first one by providing only the target path. It uses the second overloaded function for the recursive part. The code is fairly self-explanatory.
Private Overloads Function Recursive(ByVal strPath As String)
Dim oDir As New System.IO.DirectoryInfo(strPath)
Dim oSubDir() As System.IO.DirectoryInfo
Dim oFiles() As System.IO.FileInfo
Dim i As Int32
oFiles = oDir.GetFiles
For i = 0 To oFiles.Length - 1
Debug.WriteLine(oFiles(i).Name.ToString)
Next
oSubDir = oDir.GetDirectories()
For i = 0 To oSubDir.Length - 1
Debug.WriteLine(oSubDir(i).Name.ToString)
'more code to do whatever here
Call Recursive(oSubDir(i), 1)
Next
End Function
Private Overloads Function Recursive(ByVal oDir As System.IO.DirectoryInfo, ByVal intLevel As Int32)
Dim oSubDir() As System.IO.DirectoryInfo
Dim oFiles() As System.IO.FileInfo
Dim i As Int32
oFiles = oDir.GetFiles
For i = 0 To oFiles.Length - 1
Debug.WriteLine(New String(" ", intLevel) & ">" & oFiles(i).Name.ToString)
Next
oSubDir = oDir.GetDirectories()
For i = 0 To oSubDir.Length - 1
Debug.WriteLine(New String(" ", intLevel) & oSubDir(i).Name.ToString)
'more code to do whatever here
Call Recursive(oSubDir(i), intLevel + 1)
Next
End Function