Introduction

I have spent numerous hours searching for solutions to programming problems that I think should have a more accessible solution. This blog will contain my experiences and the solutions that I found. Your comments are welcome of course.

Thursday, January 24, 2008

Get a Tree View of Folder Structure using Visual Basic 2005

I wanted to create a form that contains a tree view. The tree view would then build a list of all the folders on a particular drive selected. I ran into a few problems with writing this code. Mainly, that when the program tries to read information from the "System Volume Information" folder it returns an exception. The following code shows how to get around this problem and create the list.
The tree generation is started by clicking a button called btnRead. I also have a control on the form called tvFolders (TreeView Folders).

Imports System.IO

Private Sub BuildFolderTree(ByVal frmNode As Tree, ByVal curPath As String)

Dim curDirInfo As DirectoryInfo
Dim newFolder As TreeNode
Dim curFolder As String
Dim subFolder As String

Try
For Each curFolder In My.Computer.FileSystem.GetDirectories(curPath)
subFolder = My.Computer.FileSystem.GetDirectories(curFolder)
curDirInfo = My.Computer.FileSystem.GetDirectoryInfo(curFolder)
If Not (curDirInfo.Attributes = 22 Or curDirInfo.Attributes = FileAttributes.Hidden) Then

If frmNode Is Nothing Then

newFolder = tvFolders.Nodes.Add(subFolder)

Else

newFolder = frmNode.Nodes.Add(subFolder)

End If
BuildFolderTree(newFolder, My.Computer.FileSystem.CombinePath(curPath, subFolder))

End If

Next curFolder

Catch curEx As Security.SecurityException
' You can put a warning message here or just ignore it.
Catch curEx As UnauthorizedAccessException
' You can put a warning message here or just ignore it.

System.Windows.Forms.Application.DoEvents()

End Sub

This code shows also how Recursive Programming works. In order for the tree to be built, the program has to recursively go through each folder and check and see if it has sub folders. If it does a tree has to be built for that subfolder as well. This is the reason for having a BuildFolderTree sub procedure call in the middle of the sub procedure.

One Part I am not sure about is the curDirInfo.Attributes = 22. I did some research to find out why the attribute is equal to 22 but I could not find anything about a Folder Attribute equaling 22. The list of folder Attributes are as follows and doesn't include a 22.

Normal 0
ReadOnly 1
Hidden 2
System 4
Volume 8
Directory 16
Archive 32
Alias 64
Compressed 128

No comments: