在树视图中显示所有驱动器、文件和子文件夹 [英] Display all drives, files, and subfolders in treeview

查看:26
本文介绍了在树视图中显示所有驱动器、文件和子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在树视图中显示所有驱动器、文件和子文件夹的最简单方法.如果有人有一段代码可以做到这一点,并且他们不介意分享,我会非常感激.

I'm looking for the simplest way to display all drives, files, and subfolders in a treeview. If someone's got a snippet of code to do this that they don't mind sharing I would really appreciate it.

我得到的最接近的是我尝试使用的这段代码,但它给了我一个IOException 未处理"错误,说设备未准备好".运行时错误(大约 5-10 秒后)在下面的行

The closest I've gotten was this code I tried using, but it gave me a "IOException was unhandled" error saying "The device is not ready." error at runtime (after about 5-10 sec) on the line below

Dim folders() As String = IO.Directory.GetDirectories(dir)

下面是其余的代码

Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim drives As System.Collections.ObjectModel.ReadOnlyCollection(Of IO.DriveInfo) = My.Computer.FileSystem.Drives
    Dim rootDir As String = String.Empty
    For i As Integer = 0 To drives.Count - 1
        rootDir = drives(i).Name
        TreeView1.Nodes.Add(rootDir)
        PopulateTreeView(rootDir, TreeView1.Nodes(i))
    Next
End Sub

Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
    Dim folder As String = String.Empty
    Try
        Dim folders() As String = IO.Directory.GetDirectories(dir)
        If folders.Length <> 0 Then
            Dim childNode As TreeNode = Nothing
            For Each folder In folders
                childNode = New TreeNode(folder)
                parentNode.Nodes.Add(childNode)
                PopulateTreeView(folder, childNode)
            Next
        End If
    Catch ex As UnauthorizedAccessException
        parentNode.Nodes.Add(folder & ": Access Denied")
    End Try
End Sub

推荐答案

看来您已经有了一个良好的开端.您收到的 IOException 很可能是由您的程序尝试列出空磁盘驱动器上的内容引起的,这显然是不可能的.

Seems like you're off to a good start. The IOException you receive is most likely caused by your procedure trying to list contents on an empty disc drive, which is obviously impossible.

修复很简单:

For i As Integer = 0 To drives.Count - 1
    If Not drives(i).IsReady Then
        Continue For
    End If
    rootDir = drives(i).Name
    TreeView1.Nodes.Add(rootDir)
    PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next

除此之外,我建议在单击节点之前不要加载文件夹内容.将递归调用限制为 1 级(当前目录 + 其所有子目录的内容).这样,您可以获得最佳性能,同时仍然能够确定子目录是否应具有树视图展开按钮.

Besides that, I recommend not loading folder contents until a node is clicked. Limit the recursive call to 1 level (current directory + content of all its subdirectories). That way, you get the best performance while still being able to determine whether a subdirectory should have the treeview expand button.

这篇关于在树视图中显示所有驱动器、文件和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆