Here’s a quick way to drop a drive’s folder hierarchy into a TreeView control. The advantage to using this method is that folders are enumerated only when a node is expanded, so your app won’t waste time adding folders the user will never look at. A dummy item is added to each folder to get a plus sign on the node, but the item is removed when the node is expanded or simply disappears if the folder has no subdirectories. This code assumes your TreeView is named tvFiles and you have a button named cmdEnum on the form. The TreeView is connected to an ImageList whose first image is a folder icon:
Private Type WIN32_FIND_DATA dwFileAttributes As Long ftCreationTime As Currency 'FILETIME ftLastAccessTime As Currency 'FILETIME ftLastWriteTime As Currency 'FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * 260 cAlternate As String * 14End TypePrivate Const FILE_ATTRIBUTE_DIRECTORY = &H10Private Declare Function FindFirstFile Lib _ "kernel32" Alias "FindFirstFileA" _ (ByVal lpFileName As String, lpFindFileData _ As WIN32_FIND_DATA) As LongPrivate Declare Function FindNextFile Lib _ "kernel32" Alias "FindNextFileA" _ (ByVal hFindFile As Long, lpFindFileData _ As WIN32_FIND_DATA) As LongPrivate Declare Function FindClose Lib _ "kernel32" (ByVal hFindFile As Long) As LongPrivate Sub EnumFilesUnder(n As Node) Dim hFind As Long Dim sPath As String, oldPath As String Dim wf As WIN32_FIND_DATA Dim n2 As Node sPath = n.FullPath & "*.*" hFind = FindFirstFile(sPath, wf) Do ' Get the filename, if any. If InStr(wf.cFileName, vbNullChar) > 0 Then sPath = Left$(wf.cFileName, _ InStr(wf.cFileName, vbNullChar) - 1) Else sPath = wf.cFileName End If If Len(sPath) = 0 Or StrComp(sPath, _ oldPath) = 0 Then ' Nothing found? Exit Do ElseIf sPath <> "." And sPath <> ".." Then ' Add file with folder image If (wf.dwFileAttributes And _ FILE_ATTRIBUTE_DIRECTORY) _ = FILE_ATTRIBUTE_DIRECTORY Then Set n2 = tvFiles.Nodes.Add(n, _ tvwChild, , wf.cFileName, 1, 1) ' Add a dummy item so the + sign is ' displayed tvFiles.Nodes.Add n2, tvwChild n2.Sorted = True End If End If FindNextFile hFind, wf oldPath = sPath Loop FindClose hFindEnd SubPrivate Sub cmdEnum_Click() tvFiles.Nodes.Clear ' Add an "initializing" item tvFiles.Nodes.Add , , , "C:", 1 tvFiles.Nodes(1).Sorted = True EnumFilesUnder tvFiles.Nodes.Item(1) ' Make sure the root is expanded tvFiles.Nodes(1).Expanded = TrueEnd SubPrivate Sub tvFiles_Expand(ByVal Node _ As ComctlLib.Node) If Node.Children = 1 Then ' Remove the "dummy" item tvFiles.Nodes.Remove Node.Child.Index ' Enumerate file system items under ' this node EnumFilesUnder Node End IfEnd Sub