Page 1 of 1

TreeView Drive, Folder, and File Explorer Rate Topic: -----

#1 IronRazer  Icon User is offline

  • Custom Control Freak
  • member icon

Reputation: 1356
  • View blog
  • Posts: 3,489
  • Joined: 01-February 13

Posted 08 January 2017 - 08:39 PM

Due to seeing several questions over my time of helping on DIC and other forums about this, i figured i would make a quick tutorial for a TreeView that can be used to navigate the Drives, Folders, and Files of the system. In addition, show the actual icons of them and let you choose what root nodes you want added to the TreeView. So, grab a big cup of coffee and lets get going...

Setting Up The Form
The first thing we will need to do is create a new Windows Forms project. Add one TreeView control, one ImageList control, and one TextBox control to the form. In the properties, name the TreeView as Tv_Explorer, name the ImageList as Tv_ImgList, and name the TextBox as TxtBx_Path. You do not need to set any other properties other than the Names of the controls. Here is how i have set the controls up on my form.
Attached Image

Adding The Iconhelper Class
Since we are going to use the actual icon images of the Drives, Folders, and Files to display next to the TreeView nodes, we will add a handy little class to the project that i have posted here on DIC at the following link -> Get Icon Images Of Files, Folders, Drives, or Registered Files. Since i have already explained a little about it and how it works at that link, you can read the details and comments there instead of me repeating it again in this tutorial.

To add the class to your project, go to the VS menu and click (Project), then from the dropdown select (Add Class). When the dialog pops up, name the class Iconhelper.vb and press (Add). You can then copy the code for the Iconhelper class from that link and paste it into the Iconhelper class you just added to your project.


Adding The Namespace Imports We Need In The Form`s Class
We will only need one Namespace imported at the top of the Form`s class for this. We need to import the System.IO Namespace since we are using a lot of classes from it. Such as the File class, Directory Class, DirectoryInfo class, FileInfo Class, and the Path Class. Go to your Form`s class code and add this Import at the very top of the code.
Imports System.IO 'add this Import

Public Class Form1

End Class




Adding Images To The ImageList
Now we can get started on the Form`s code. As i stated above we will be using the actual icons of the drives, folders, and files. That means that we could end up with thousands of icons in the ImageList which would hog a lot of memory. So, we will do a little fancy work to limit the amount of images that are needed for all the folders. For example, a standard folder icon would be the same for most folders so, we will add just one folder to the ImageList that will be used for all the standard folders in the TreeView. The ApplicationData folder is a safe folder icon to load for that since it is located on all systems and has a standard folder icon.

There are also some special folders that have special icon images, such as My Document, My Music, Favorites, and so on... We will add all these special folder images to the ImageList too. They will be used for any of the special folders. By loading all these folders right at the start, it will eliminate us from having to load new images into the ImageList for any folders after this.

As you may have noticed in the Iconhelper link above, it can load icons for file types that are registered on the system by passing just the extension of a file. For example, all files that use the .txt extension use the same registered Text icon, all .rtf file types use the same RichText icon, and so on... We will use this to our advantage to limit the images added to the ImageList too. We will only load a new file icon image when a registered file type is encountered that is not added to the ImageList already.

There is a few exceptions to using the extensions like this though. For example, the .exe, .lnk, and .url files can have different icons even though these are registered file types. So, we will need to load each of these icons as each one of these files are encountered. That is, unless we have already added the same file to the ImageList while navivigating.

So, let`s add the code that will be used to load the icons. The first sub below is used to load the icons from the Drives, Folders, and Files. It looks a little confusing but, it basically adds the icons to the ImageList and sets the ImageKey for the image to either the Extension if it is a file that is not an exe, lnk, or url type. In that case it uses the full file path and name. For a standard folder and all special folders except the Desktop folder, and the drives, it uses the full path to the Drive or Folder. For the Desktop folder there are two folders that have to be used to list all the files/folders for the current user. That has to be specially handled throughout the code. I will explain more about that in a few minutes.
    Private Function AddImageToImgList(FullPath As String, Optional SpecialImageKeyName As String = "") As String
        'If we specify a special ImageKey name when calling the sub, the ImgKey string is set to that name. Otherwise it is set to the full path.
        Dim ImgKey As String = If(SpecialImageKeyName = "", FullPath, SpecialImageKeyName)
        Dim LoadFromExt As Boolean = False

        'If a special ImageKey was not specified and the FullPath points to a File then we get the extension of the file and check
        'to see if it is not an exe, lnk, or url file type. If it is not, then we change the ImgKey to the extension of the file.
        If ImgKey = FullPath AndAlso File.Exists(FullPath) Then
            Dim ext As String = Path.GetExtension(FullPath).ToLower
            If ext <> "" AndAlso ext <> ".exe" AndAlso ext <> ".lnk" AndAlso ext <> ".url" Then
                ImgKey = Path.GetExtension(FullPath).ToLower
                LoadFromExt = True
            End If
        End If

        'If the ImageList does not contain an image with this same ImageKey name, then we add the new image to the ImageList.
        If Not Tv_ImgList.Images.Keys.Contains(ImgKey) Then
            Tv_ImgList.Images.Add(ImgKey, Iconhelper.GetIconImage(If(LoadFromExt, ImgKey, FullPath), IconSizes.Large32x32))
        End If

        'we return the ImageKey name that was used to add this image to the ImageList. This will be used when a node for a file is added to the TreeView.
        Return ImgKey
    End Function



So, now we need a sub we can call when the application is loading that will add the standard folder icon image to the ImageList along with all the Special Folder icon images.
    Private Sub AddSpecialAndStandardFolderImages()
        'Add one standard folder to the ImageList that will be used for all standard folders that are added to the ListView
        AddImageToImgList(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Folder")

        'Here we create a list of the Special Folders that have special icon images.
        Dim SpecialFolders As New List(Of Environment.SpecialFolder)
        With SpecialFolders
            .Add(Environment.SpecialFolder.Desktop)
            .Add(Environment.SpecialFolder.MyDocuments)
            .Add(Environment.SpecialFolder.Favorites)
            .Add(Environment.SpecialFolder.Recent)
            .Add(Environment.SpecialFolder.MyMusic)
            .Add(Environment.SpecialFolder.MyVideos)
            .Add(Environment.SpecialFolder.Fonts)
            .Add(Environment.SpecialFolder.History)
            .Add(Environment.SpecialFolder.MyPictures)
            .Add(Environment.SpecialFolder.UserProfile)
        End With

        'Now we iterate through the list of special folders and add these icon images to the ImageList
        For Each sf As Environment.SpecialFolder In SpecialFolders
            AddImageToImgList(Environment.GetFolderPath(sf))
        Next
    End Sub




Adding The Root Drive Nodes
Let`s move on to adding some Nodes to the TreeView. Of coarse we will want a sub that we can call to add the root nodes for all the Hard Drives, Removable Drives, CD and DVD-ROMs, and such. It is pretty basic, just iterate through the drives, add the drives icon to the ImageList, create a new TreeNode for the drive, and add it to the TreeView.
    Private Sub AddDriveRootNodes()
        For Each drv As DriveInfo In DriveInfo.GetDrives 'iterate through all the drives on the system
            AddImageToImgList(drv.Name) 'add the drive icon image to the ImageList
            Dim DriveNode As New TreeNode(drv.Name) 'create a new TreeNode for the drive
            With DriveNode
                .Tag = drv.Name 'set the Tag property to the name of the drive (C:\, D:\, and so on...)
                .ImageKey = drv.Name 'set the ImageKey to the name of the drive which is the ImageKey name that is used to add the image to the ImageList
                .SelectedImageKey = drv.Name
                .Nodes.Add("Empty") 'we will add an empty child node to this node so that the node shows the box to expand it in the TreeView
            End With
            Tv_Explorer.Nodes.Add(DriveNode) 'add the drive node to the TreeView
        Next
    End Sub




Adding Special Folders As Root Nodes
What if we want to add some of the Special Folders as root nodes in the TreeView? Well, we can do that too. We just need another sub we can call and pass the Special Folder we want to add as a root node. However, not all the Special folders can be used in this case so, we will add some of the common ones to our own Enumeration (Enum) that we will use to specify the Special Folder.

The sub will basically just get the folder path and the folder name to use for adding the icon Image to the ImageList and add the TreeNode for the folder to the TreeView. The icon image will not be added to the ImageList if it already contains the image though. The TreeNode will just use the one that is already added in that case.
    Private Enum SpecialNodeFolders As Integer
        Desktop = Environment.SpecialFolder.Desktop
        Favorites = Environment.SpecialFolder.Favorites
        History = Environment.SpecialFolder.History
        MyDocuments = Environment.SpecialFolder.MyDocuments
        MyMusic = Environment.SpecialFolder.MyMusic
        MyPictures = Environment.SpecialFolder.MyPictures
        MyVideos = Environment.SpecialFolder.MyVideos
        Recent = Environment.SpecialFolder.Recent
        UserProfile = Environment.SpecialFolder.UserProfile
    End Enum

    Private Sub AddSpecialFolderRootNode(SpecialFolder As SpecialNodeFolders)
        'get the actual folder path for this Special Folder
        Dim SpecialFolderPath As String = Environment.GetFolderPath(CType(SpecialFolder, Environment.SpecialFolder))

        'Get just the name of the folder such as (Desktop, Documents, Pictures... you get the point)
        Dim SpecialFolderName As String = Path.GetFileName(SpecialFolderPath)

        'Add the image of the special folder. It is only added if the ImageList does not already contain this image.
        AddImageToImgList(SpecialFolderPath, SpecialFolderName)

        Dim DesktopNode As New TreeNode(SpecialFolderName) 'Create the new TreeNode for this folder.
        With DesktopNode
            .Tag = SpecialFolderPath 'set the Tag to the full path to this folder.
            .ImageKey = SpecialFolderName 'set the ImageKey to the ImageKey that was used when the image was added to the ImageList
            .SelectedImageKey = SpecialFolderName
            .Nodes.Add("Empty") 'add an empty child node so that this node shows the box for expanding the node
        End With

        Tv_Explorer.Nodes.Add(DesktopNode) 'add the folder node to the TreeView
    End Sub





Adding Child Nodes To The Root Nodes
Now that we have a way to add the root nodes to the TreeView, we will need a way to populate them with the child nodes when we expand a root node. We will use the TreeView`s BeforeExpand event to do that. First we will need a sub that we can call from the BeforeExpand event that will populate them. Looking at the BeforeExpand event of the TreeView, you will see that the second parameter, the e parameter that is passed into the event is a TreeViewCancelEventArgs Class which we can get the node that is expanding from.

We will make our sub that adds the child nodes so that we can pass the node that raised the event to it in one parameter. We will also make the sub so it takes a second parameter that we can pass the full path of the drive or folder that the node represents. This second parameter would not be needed if we did not have to handle the Desktop folder which has to be populated from two different folders. I will explain more about that in a few minutes. Let`s add the sub for this.
    Private Sub AddChildNodes(tn As TreeNode, DirPath As String)
        Dim DirInfo As New DirectoryInfo(DirPath) 'Create a new DirectoryInfo class for the directory

        'We will place the code that iterates through the sub directories and files in a Try Catch because we might run into a folder or file
        'that we do not have the proper permissions to access. This will stop the code from throwing an exception and crashing our application.
        'We will use the Catch to handle any exceptions and let the user know what happened. Then the program can continue.
        Try
            For Each di As DirectoryInfo In DirInfo.GetDirectories 'iterate through sub folders of this directory or drive

                If Not (di.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then 'Make sure it is not a hidden folder, we don`t want them
                    Dim FolderNode As New TreeNode(di.Name) 'ceate a new TreeNode for the folder
                    With FolderNode
                        .Tag = di.FullName 'add the full folder path to the Tag property

                        'If the ImageList contains an ImageKey for this folder path, we want to use the full path for the ImageKey of this node
                        If Tv_ImgList.Images.Keys.Contains(di.FullName) Then
                            .ImageKey = di.FullName
                            .SelectedImageKey = di.FullName

                        Else 'if the ImageList does not contain this folder path it would mean it is not a Special Folder, so we want to use the standard Folder image
                            .ImageKey = "Folder"
                            .SelectedImageKey = "Folder"
                        End If

                        .Nodes.Add("*Empty*") 'add an empty node to this child node so it can be expanded in the TreeView

                    End With
                    tn.Nodes.Add(FolderNode) 'add this folder node to the node that was expanded, the one passed to this sub
                End If
            Next

            For Each fi As FileInfo In DirInfo.GetFiles 'iterate through the files in this directory or drive

                If Not (fi.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then 'Make sure it is not a hidden file, we don`t want them

                    'here is where we need to use the returned ImageKey that was used in the AddImageToImgList function to add the image to the ImageList.
                    'If you remember, if it is a registered file other than an exe, lnk, or url file type, the ImageKey name will be the extension of the file.
                    'Otherwise, it will be the full path to the file that is used to add the image to the ImageList.
                    Dim ImgKey As String = AddImageToImgList(fi.FullName)

                    Dim FileNode As New TreeNode(fi.Name) ' create a new TreeNode for this file
                    With FileNode
                        .Tag = fi.FullName 'add the full path to the file to the Tag property
                        .ImageKey = ImgKey 'we need to use the same ImageKey name that was used to add the image to the ImageList
                        .SelectedImageKey = ImgKey
                    End With
                    tn.Nodes.Add(FileNode) 'add this file node to the node that was expanded, the one passed to this sub
                End If
            Next

        Catch ex As Exception 'if an exception was thrown trying to access a folder or file, let the user know what exception was thrown
            MessageBox.Show(ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub




Now let`s move back to the TreeView`s BeforeExpand event which calls the sub to add the child nodes. This is where we use the Node passed into the BeforeExpande event i mentioned a few minutes ago. If you have been paying attention, you will remember that when we added the root nodes to the TreeView, we have been setting the Tag property of them to the full path of the drive and special folder nodes. We have also been setting the ImageKey names of them too. We can use those two properties to determine if this node is a folder or a drive, and if the drive is ready to be accessed.

This is where i will explain the special handling of the Desktop folder node i have been mentioning. If a program is installed on the computer for all the users of the computer and it creates a desktop shortcut, the shortcut will be placed in the CommonDesktopDirectory which is located at "C:\Users\Public\Desktop". However, if a program is installed on the computer for just the current user and a desktop shortcut is created, it will be placed in the current user`s Desktop directory which is located at "C:\Users\CurrentUsersName\Desktop". The system places the shortcuts from both folders on the current users desktop. So, we need to do the same thing in order to make sure all the shortcuts are listed under our Desktop node. So, let`s add the BeforeExpand event sub for our TreeView.
    Private Sub TV_Explorer_BeforeExpand(sender As Object, e As TreeViewCancelEventArgs) Handles Tv_Explorer.BeforeExpand
        'making use of LINQ we can get a boolean value of True/False that we can use to determine if the node is a drive and is ready to be accessed.
        'CD and DVD-ROMs will throw an exception if you try accessing anything other than their name if there is not a disc in the drive.
        Dim DrvIsReady As Boolean = (From d As DriveInfo In DriveInfo.GetDrives Where d.Name = e.Node.ImageKey Select d.IsReady).FirstOrDefault

        'if the node is not the Desktop node and does not contain a full folder path, or if it is a drive that is ready, or if the directory path
        'exists, we can add the child nodes to it from a single path that it`s Tag property has been set to.
        If (e.Node.ImageKey <> "Desktop" AndAlso Not e.Node.ImageKey.Contains(":\")) OrElse DrvIsReady OrElse Directory.Exists(e.Node.ImageKey) Then
            e.Node.Nodes.Clear() 'clear the "Empty" child node from this node
            AddChildNodes(e.Node, e.Node.Tag.ToString) 'call our sub to add the child nodes to this node

        ElseIf e.Node.ImageKey = "Desktop" Then 'if the node is the Desktop node, we need to add the child nodes from two different folders.
            e.Node.Nodes.Clear() 'clear the "Empty" child node from this node

            'If a program was installed on the computer for all useres, the desktop shortcut will be placed in the CommonDesktopFolder. If a program was
            'installed for the current user only, then the desktop shortcut would be placed in the Desktop folder. So, we need to add the child nodes to
            'this node from two different folders in order to make sure we get all the shortcuts that the user sees on their desktop.
            Dim PublicDesktopFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)
            Dim CurrentUserDesktopFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            AddChildNodes(e.Node, CurrentUserDesktopFolder)
            AddChildNodes(e.Node, PublicDesktopFolder)

        Else 'if it makes it to the Else part, it indicates that it must be a CD or DVD-ROM drive that is not ready (No disc in the drive).
            e.Cancel = True 'cancel the node from expanding and then let the user know why
            MessageBox.Show("The CD or DVD drive is empty.", "Drive Info...", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub




Before moving on, we will also want to handle the AfterCollapse event of our TreeView too. We will use this event to remove all the nodes from the node that is collapsing and to add the "Empty" child node to it again. If you where paying attention when we added the subs for adding drive and folder nodes to the TreeView, we added the empty node just so that the (+) box is shown on the node and we can expand it. Without the empty node we would not be able to expand the drive or folder nodes. The reason we remove all the nodes that are not being shown anymore is to reduce any memory usage they may be hogging up. Let`s add that event now.
    Private Sub TV_Explorer_AfterCollapse(sender As Object, e As TreeViewEventArgs) Handles Tv_Explorer.AfterCollapse
        e.Node.Nodes.Clear()
        e.Node.Nodes.Add("Empty")
    End Sub




Using TreeView Events To Do Something With The Nodes
I am sure you want to do more than just look at the nodes in the TreeView so, here i will show how you can use a few of the TreeView events to make use of the TreeView. First, we will use the AfterSelect event of the TreeView to display the full path from the node that is selected in a TextBox. We can use the second parameter that was passed into the AfterSelect event to get the full path to the Drive, Folder, or File from the selected node. Let`s add that event.
    Private Sub TV_Explorer_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles Tv_Explorer.AfterSelect
        TxtBx_Path.Text = e.Node.Tag.ToString
    End Sub




Now let`s use the MouseDoubleClick event to actually start the exe files or the default programs for the double clicked files. The default programs are the programs that are used to open the files you double click. For example, if you double click a text file (.txt), then Notepad would be started with that file opened in it. If you double click an MS Ofice document (.doc), then MS office would open with that document loaded. And of coarse, if you double clicked a program`s exe file, that program would be run. You get the point, so let`s add that event now.
    Private Sub TV_Explorer_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles Tv_Explorer.NodeMouseDoubleClick
        'Make sure it is the left mouse button that was double clicked and that the node is a File node.
        If e.Button = MouseButtons.Left AndAlso File.Exists(e.Node.Tag.ToString) Then

            'we will use a Try Catch here just in case we run into a problem such as there not being a program registered on the system to
            'open the file type that we double click. Files like a (.dll) are not meant to be opened or ran and would give you this messege.
            Try
                Process.Start(e.Node.Tag.ToString) 'start the program exe or the default program for the double clicked file type
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub




Calling The Subs To Add The Root Nodes
We can now get to the final missing puzzle piece, calling our subs to add the Special Folders and Standard Folder icon images to the ImageList and to add the root nodes to the TreeView. We will use the Load event of the form to do this. If you remember, we have two subs to add root nodes. One to add the Drives and one to add Special Folders. This will allow us to customize the root nodes that are shown in the TreeView. For example, if you only wanted the "Pictures" folder to be shown for a program that deals with Saving/Loading images, you can just call the AddSpecialFolderRootNode sub and set it`s parameter to the SpecialNodeFolders.MyPictures from our custom SpecialNodeFolders enumeration.
AddSpecialFolderRootNode(SpecialNodeFolders.MyPictures)


You can add any combination of the SpecialNodeFolders. For example, to add the Pictures, Videos, and Music folders you would do this.
        AddSpecialFolderRootNode(SpecialNodeFolders.MyPictures)
        AddSpecialFolderRootNode(SpecialNodeFolders.MyVideos)
        AddSpecialFolderRootNode(SpecialNodeFolders.MyMusic)



If you only wanted the Drives to be added to the TreeView, you would just call the AddDriveRootNodes sub.
        AddDriveRootNodes()



You could also add any combination of the SpecialNodeFolders along with the Drives.
        AddSpecialFolderRootNode(SpecialNodeFolders.Desktop)
        AddSpecialFolderRootNode(SpecialNodeFolders.MyDocuments)
        AddDriveRootNodes()



Let`s add the Load event and some code so we can start running the application and see the rewards of all our work.
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Tv_ImgList.ImageSize = New Size(20, 20) 'we will set the size for the icon images to 20x20 just to make them easier to see clearly
        Tv_Explorer.ImageList = Tv_ImgList 'we need to set the ImageList property of the TreeView to our ImageList that will contain all the icon images.

        AddSpecialAndStandardFolderImages() 'now add the Special Folder and Standard folder icon images to the Image list before you add any root nodes.

        'just to get going, let`s add the Desktop and Documents folder along with all the Drives to the TreeView as root nodes. Even though you could
        'navigate through the drives to get to the two folders, it can be handy to have quicker access to these folders without navigating through the
        'drives to get to them every time.
        AddSpecialFolderRootNode(SpecialNodeFolders.Desktop) 'add the first root node in the TreeView
        AddSpecialFolderRootNode(SpecialNodeFolders.MyDocuments) 'add the second root node to the TreeView
        AddDriveRootNodes() 'add the Drives as the third, fourth, and so on... root nodes
    End Sub




Final Results
Here is the final code of the Form Class without all the comments. It does not include the Iconhelper class which you can find at the link i posted in the "Adding The Iconhelper Class" section at the start of the tutorial. The image below the code shows what the final outcome will look like.
Imports System.IO

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Tv_ImgList.ImageSize = New Size(20, 20)
        Tv_Explorer.ImageList = Tv_ImgList

        AddSpecialAndStandardFolderImages()

        AddSpecialFolderRootNode(SpecialNodeFolders.Desktop)
        AddSpecialFolderRootNode(SpecialNodeFolders.MyDocuments)
        AddDriveRootNodes()
    End Sub

    Private Sub TV_Explorer_BeforeExpand(sender As Object, e As TreeViewCancelEventArgs) Handles Tv_Explorer.BeforeExpand
        Dim DrvIsReady As Boolean = (From d As DriveInfo In DriveInfo.GetDrives Where d.Name = e.Node.ImageKey Select d.IsReady).FirstOrDefault

        If (e.Node.ImageKey <> "Desktop" AndAlso Not e.Node.ImageKey.Contains(":\")) OrElse DrvIsReady OrElse Directory.Exists(e.Node.ImageKey) Then
            e.Node.Nodes.Clear()
            AddChildNodes(e.Node, e.Node.Tag.ToString)

        ElseIf e.Node.ImageKey = "Desktop" Then
            e.Node.Nodes.Clear()
            Dim PublicDesktopFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)
            Dim CurrentUserDesktopFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            AddChildNodes(e.Node, CurrentUserDesktopFolder)
            AddChildNodes(e.Node, PublicDesktopFolder)

        Else
            e.Cancel = True
            MessageBox.Show("The CD or DVD drive is empty.", "Drive Info...", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub TV_Explorer_AfterCollapse(sender As Object, e As TreeViewEventArgs) Handles Tv_Explorer.AfterCollapse
        e.Node.Nodes.Clear()
        e.Node.Nodes.Add("Empty")
    End Sub

    Private Sub TV_Explorer_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles Tv_Explorer.AfterSelect
        TxtBx_Path.Text = e.Node.Tag.ToString
    End Sub

    Private Sub TV_Explorer_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles Tv_Explorer.NodeMouseDoubleClick
        If e.Button = MouseButtons.Left AndAlso File.Exists(e.Node.Tag.ToString) Then
            Try
                Process.Start(e.Node.Tag.ToString)
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub

    Private Sub AddSpecialFolderRootNode(SpecialFolder As SpecialNodeFolders)
        Dim SpecialFolderPath As String = Environment.GetFolderPath(CType(SpecialFolder, Environment.SpecialFolder))
        Dim SpecialFolderName As String = Path.GetFileName(SpecialFolderPath)

        AddImageToImgList(SpecialFolderPath, SpecialFolderName)

        Dim DesktopNode As New TreeNode(SpecialFolderName)
        With DesktopNode
            .Tag = SpecialFolderPath
            .ImageKey = SpecialFolderName
            .SelectedImageKey = SpecialFolderName
            .Nodes.Add("Empty")
        End With

        Tv_Explorer.Nodes.Add(DesktopNode)
    End Sub

    Private Sub AddDriveRootNodes()
        For Each drv As DriveInfo In DriveInfo.GetDrives
            AddImageToImgList(drv.Name)
            Dim DriveNode As New TreeNode(drv.Name)
            With DriveNode
                .Tag = drv.Name
                .ImageKey = drv.Name
                .SelectedImageKey = drv.Name
                .Nodes.Add("Empty")
            End With
            Tv_Explorer.Nodes.Add(DriveNode)
        Next
    End Sub

    Private Sub AddChildNodes(tn As TreeNode, DirPath As String)
        Dim DirInfo As New DirectoryInfo(DirPath)
        Try
            For Each di As DirectoryInfo In DirInfo.GetDirectories
                If Not (di.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
                    Dim FolderNode As New TreeNode(di.Name)
                    With FolderNode
                        .Tag = di.FullName
                        If Tv_ImgList.Images.Keys.Contains(di.FullName) Then
                            .ImageKey = di.FullName
                            .SelectedImageKey = di.FullName
                        Else
                            .ImageKey = "Folder"
                            .SelectedImageKey = "Folder"
                        End If
                        .Nodes.Add("*Empty*")
                    End With
                    tn.Nodes.Add(FolderNode)
                End If
            Next
            For Each fi As FileInfo In DirInfo.GetFiles
                If Not (fi.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
                    Dim ImgKey As String = AddImageToImgList(fi.FullName)
                    Dim FileNode As New TreeNode(fi.Name)
                    With FileNode
                        .Tag = fi.FullName
                        .ImageKey = ImgKey
                        .SelectedImageKey = ImgKey
                    End With
                    tn.Nodes.Add(FileNode)
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub AddSpecialAndStandardFolderImages()
        AddImageToImgList(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Folder")

        Dim SpecialFolders As New List(Of Environment.SpecialFolder)
        With SpecialFolders
            .Add(Environment.SpecialFolder.Desktop)
            .Add(Environment.SpecialFolder.MyDocuments)
            .Add(Environment.SpecialFolder.Favorites)
            .Add(Environment.SpecialFolder.Recent)
            .Add(Environment.SpecialFolder.MyMusic)
            .Add(Environment.SpecialFolder.MyVideos)
            .Add(Environment.SpecialFolder.Fonts)
            .Add(Environment.SpecialFolder.History)
            .Add(Environment.SpecialFolder.MyPictures)
            .Add(Environment.SpecialFolder.UserProfile)
        End With

        For Each sf As Environment.SpecialFolder In SpecialFolders
            AddImageToImgList(Environment.GetFolderPath(sf))
        Next
    End Sub

    Private Function AddImageToImgList(FullPath As String, Optional SpecialImageKeyName As String = "") As String
        Dim ImgKey As String = If(SpecialImageKeyName = "", FullPath, SpecialImageKeyName)
        Dim LoadFromExt As Boolean = False

        If ImgKey = FullPath AndAlso File.Exists(FullPath) Then
            Dim ext As String = Path.GetExtension(FullPath).ToLower
            If ext <> "" AndAlso ext <> ".exe" AndAlso ext <> ".lnk" AndAlso ext <> ".url" Then
                ImgKey = Path.GetExtension(FullPath).ToLower
                LoadFromExt = True
            End If
        End If

        If Not Tv_ImgList.Images.Keys.Contains(ImgKey) Then
            Tv_ImgList.Images.Add(ImgKey, Iconhelper.GetIconImage(If(LoadFromExt, ImgKey, FullPath), IconSizes.Large32x32))
        End If

        Return ImgKey
    End Function

    Private Enum SpecialNodeFolders As Integer
        Desktop = Environment.SpecialFolder.Desktop
        Favorites = Environment.SpecialFolder.Favorites
        History = Environment.SpecialFolder.History
        MyDocuments = Environment.SpecialFolder.MyDocuments
        MyMusic = Environment.SpecialFolder.MyMusic
        MyPictures = Environment.SpecialFolder.MyPictures
        MyVideos = Environment.SpecialFolder.MyVideos
        Recent = Environment.SpecialFolder.Recent
        UserProfile = Environment.SpecialFolder.UserProfile
    End Enum
End Class


Attached Image

Is This A Good Question/Topic? 4
  • +

Replies To: TreeView Drive, Folder, and File Explorer

#2 SG-1 Charpy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • Posts: 1
  • Joined: Yesterday, 03:43 PM

Posted Yesterday, 03:53 PM

:D Hi, thanks for this tutorial, it's help me a lot for create my custom TreeView Controls.
When its was finished, i post the final result in this forum. Be patient, i'm a newbie in VB.net.
Sorry for my poor English.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1