【问题标题】:Get all the folders and sub-folders and files in a directory Vb.Net获取目录 Vb.Net 中的所有文件夹和子文件夹和文件
【发布时间】:2020-04-28 18:13:52
【问题描述】:

如何获取特定路径目录中的所有文件夹和子文件夹和文件?,

示例:

+ folder1
 - exe1
 + folder2
  - exe1
  - exe2
  + folder3
   - exe1

+ folder2
 - exe1

+ folder3

+ folder4

我现在正在使用:

Sub GetDirectories(ByVal StartPath As String)
        For Each Dir As String In IO.Directory.GetDirectories(StartPath)
            ListBox1.Items.Add(Dir)
            ListBox1.Items.AddRange(IO.Directory.GetFiles(StartPath))
            ListBox1.Items.AddRange(IO.Directory.GetFiles(Dir))
        Next
    End Sub

和:

Dim files() As String = e.Data.GetData(DataFormats.FileDrop)

        For Each path In files

            For Each Dir As String In IO.Directory.GetDirectories(path)
                GetDirectories(path)
            Next

        Next

但它没有给我其他子文件夹中的所有文件。

编辑: 与列表框一起使用,我想在放入文件夹时查看完整路径,然后给出所有子文件夹和文件

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您可以更好地使用TreeView 以获得更方便的结果。

    只需从工具箱中获取TreeView 并使用以下代码列出特定目录和子目录(包括文件):

    Private Enum ItemType
        Drive
        Folder
        File
    End Enum
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim node As TreeNode =
        TreeView1.Nodes.Add("Hello") ' Specifying Folder Names
        node.Tag = ItemType.Folder
        node.Nodes.Add("FILLER")
    End Sub
    
    Private Sub file_view_tree_BeforeExpand(sender As Object, e As TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
    
        Dim currentNode As TreeNode = e.Node
        currentNode.Nodes.Clear()
    
        Try
            'Now go get all the files and folders
            Dim fullPathString As String = currentNode.FullPath
    
            'Handle each folder
            For Each folderString As String In
                Directory.GetDirectories(fullPathString)
    
                Dim newNode As TreeNode =
                currentNode.Nodes.Add(Path.GetFileName(folderString))
                Dim x As String = Path.GetFileName("")
                newNode.Tag = ItemType.File
                newNode.Nodes.Add("FILLER")
            Next
    
            'Handle each file
            For Each fileString As String In
                Directory.GetFiles(fullPathString)
                'Get just the file name portion (without the path) :
                Dim newNode As TreeNode =
                    currentNode.Nodes.Add(Path.GetFileName(fileString))
                newNode.Tag = ItemType.File
            Next
        Catch ex As Exception
    
        End Try
    End Sub
    

    注意:我已经修改了 Stack Overflow 的 this 线程,并根据您的要求进行了定制。

    【讨论】:

    • 我与列表框一起使用的点,我想在放入文件夹时查看完整路径,然后给出所有子文件夹和文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2023-03-31
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多