title: Recursive search for all folders and subfolders in system
body: <p>I wrote a Windows Forms script that searched for all non-hidden and non-readonly folders in my system. But the script itself, when run initially, runs for like 5 minutes. Subsequent opens take much less time. I was wondering if there is a logical error to it, so as to why its running so very slow.</p>
  
  <pre><code>Private Function FindSubFolders(ByVal dir As DirectoryInfo, ByVal node As TreeNode) As TreeNode
      Dim subnode As New TreeNode
      For Each folder As DirectoryInfo In dir.GetDirectories()
          If (folder.Attributes And FileAttributes.Hidden) &lt;&gt; FileAttributes.Hidden Then
              subnode = node.Nodes.Add(folder.FullName, folder.Name)
              subnode = FindSubFolders(folder, subnode)
          End If
      Next
      Return subnode
  End Function
  
  Private Sub SetFolders_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  
      'Is it possible to load this on 1st (initial) form load???
  
      Try
          Dim node As TreeNode
          If TreeView1.Nodes.Count &lt; 1 Then
              For Each drive As String In Directory.GetLogicalDrives
                  Directory.GetLogicalDrives()
                  Dim folders As DirectoryInfo = New DirectoryInfo(drive)
                  If (folders.Attributes And FileAttributes.ReadOnly) &lt;&gt; FileAttributes.ReadOnly Then
                      node = TreeView1.Nodes.Add(drive, drive)
                      Try
                          node = FindSubFolders(folders, node)
                      Catch ex As Exception
                          Console.WriteLine(ex.Message)
                          Continue For
                      End Try
                  End If
              Next
          End If
          If Not IsNothing(My.Settings.Folders) Then
              If ListBox1.Items.Count &lt; 1 Then
                  For Each col As String In My.Settings.Folders
                      ListBox1.Items.Add(col)
                  Next
              End If
          Else
              My.Settings.Folders = New StringCollection
          End If
      Catch ex As Exception
          Logs.Add("04", ex.Message)
      End Try
      Logs.Add("01", "Loaded.")
  End Sub
  </code></pre>
  
  <p>Thanks for the help! :)</p>