VB.NET 05, List Folder, SubFolders, and Sub SubFolders

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pbrown
    New Member
    • Aug 2007
    • 5

    VB.NET 05, List Folder, SubFolders, and Sub SubFolders

    Hey All,

    My problem appears to be pretty simple. I need a way of listing all the folders that exist in a certain directory. By all the folders, I mean ALL the folders; any file folder that exists underneath a certain directory needs to be returned, no matter how deep it lies. So, for example,


    2 folders in drive X:, one called 'Names' the other called 'Addresses'

    'Names' contains 3 different folders, each of which has 2 subfolders of its own

    'Addresses' contains 2 different folders, which have no subfolders.


    I'm searching for a way to return all the folder paths to a single array. Is there a simple method that accomplishes this? I've been playing around with 'System.IO.Dire ctory.GetDirect ories', but this allows me to only drill down one layer, so to speak.

    This seems to me like it would be a pretty common task, so I'm curious as to why I can't seem to find a solution on the net (perhaps my googling skills are sub par) Any help would be fantastic.

    Running Visual Studio 2005, on XP Pro, .NET Framework 2.0

    Thanks Guys/Gals.
  • user232k2038
    New Member
    • Sep 2007
    • 16

    #2
    The most efficient way would be to use recursivity:
    Code:
        Private Function getAllFolders(ByVal directory As String) As String()
            'Create object
            Dim fi As New IO.DirectoryInfo(directory)
            'Array to store paths
            Dim path() As String = {}
            'Loop through subfolders
            For Each subfolder As IO.DirectoryInfo In fi.GetDirectories()
                'Add this folders name
                Array.Resize(path, path.Length + 1)
                path(path.Length - 1) = subfolder.FullName
                'Recall function with each subdirectory
                For Each s As String In getAllFolders(subfolder.FullName)
                    Array.Resize(path, path.Length + 1)
                    path(path.Length - 1) = s
                Next
            Next
            Return path
        End Function

    Comment

    • user232k2038
      New Member
      • Sep 2007
      • 16

      #3
      In regard to my last post, perhaps not the most efficient, but certainly the simplest. This may get slow if you're trying to use it on large directories like C:, but for the most part it should be OK.

      Comment

      Working...