gpt4 book ai didi

vb.net - 无法列出子目录

转载 作者:行者123 更新时间:2023-12-01 01:57:39 25 4
gpt4 key购买 nike

目前它编译正确但是当我运行打开它并单击按钮时它会将所有文件从 C:\添加到 CheckedListBox1 但然后停止...

Imports System.IO

Public Class Form1
Public Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GetProfiles_Button.Click
Dim rootObject As String() = Directory.GetFiles("C:\")
For Each subObject As String In rootObject
searchObject(subObject)
Next
End Sub

Public Shared Sub searchObject(targetObject As String)
If File.GetAttributes(targetObject) = FileAttributes.Directory Then
Form1.CheckedListBox2.Items.Add(targetObject)
Dim subRoot As String() = Directory.GetFiles(targetObject)
For Each subRootObject As String In subRoot
searchObject(subRootObject)
Next
Else
Form1.CheckedListBox1.Items.Add(targetObject)
End If
End Sub

End Class

最佳答案

您正在使用 Directory.GetFiles 函数。根据documentation on MSDN ,这只会返回文件。您对 FileAttributes.Directory 枚举的检查将始终返回 false。

网上有很多例子可以在 c# 和 vb.net 中显示递归文件和目录列表。

免责声明:我从 Dot Net Perls 网站复制了这段代码 here ,而不仅仅是链接到代码(以防链接失效)。

递归目录的程序:VB.NET

Imports System.IO

''' <summary>
''' This class contains directory helper method(s).
''' </summary>
Public Class FileHelper

''' <summary>
''' This method starts at the specified directory, and traverses all subdirectories.
''' It returns a List of those directories.
''' </summary>
Public Shared Function GetFilesRecursive(ByVal initial As String) As List(Of String)
' This list stores the results.
Dim result As New List(Of String)

' This stack stores the directories to process.
Dim stack As New Stack(Of String)

' Add the initial directory
stack.Push(initial)

' Continue processing for each stacked directory
Do While (stack.Count > 0)
' Get top directory string
Dim dir As String = stack.Pop
Try
' Add all immediate file paths
result.AddRange(Directory.GetFiles(dir, "*.*"))

' Loop through all subdirectories and add them to the stack.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
stack.Push(directoryName)
Next

Catch ex As Exception
End Try
Loop

' Return the list
Return result
End Function

End Class

Module Module1

''' <summary>
''' Entry point that shows usage of recursive directory function.
''' </summary>
Sub Main()
' Get recursive List of all files starting in this directory.
Dim list As List(Of String) = FileHelper.GetFilesRecursive("C:\Users\Sam\Documents\Perls")

' Loop through and display each path.
For Each path In list
Console.WriteLine(path)
Next

' Write total number of paths found.
Console.WriteLine(list.Count)
End Sub

End Module

关于vb.net - 无法列出子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com