1

如何将目录列表存储到数组中?我已经尝试过这种方法,但这不起作用。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim parentinfo As New DirectoryInfo("C:\myfiles")

    counter1 = My.Computer.FileSystem.GetFiles("C:\myfiles")
    dirsize = counter1.Count

    ReDim directory(dirsize)

    For Each dir As FileSystemInfo In parentinfo.GetFileSystemInfos()
        Dim i As Integer = 0
        directory(i) = dir.Name
        ComboBox1.Items.Add(directory(i))
        i += 1
    Next dir

End Sub
4

1 回答 1

0

尝试做这样的事情:

Public Sub New()

    Dim directories As New List(Of DirectoryInfo)

    Call Me.InitializeComponent()

    Call Me.ComboBox1.Items.Clear()
    For Each directory As DirectoryInfo In (New DirectoryInfo("C:\")).GetDirectories()
        Call directories.Add(directory)
        Me.ComboBox1.Items.Add(directory.Name)
    Next

End Sub

这将为在指定路径中找到的所有目录生成对象列表directoriesDirectoryInfo它还将所有目录名称添加到组合框(在本例中为Combobox1.

更新

刚刚意识到您专门要求了一个数组。您可以使用ToArray()扩展方法将列表转换为数组。所以在这种情况下,在 sub 的末尾你可以调用directories.ToArray()来获取你的数组。或者,您可以将我编写的代码与数组一起使用,但坦率地说,如果可以使用列表,为什么还要使用数组呢?

如果你想用数组来做,这里是代码:

Public Sub New()

    Dim i as integer

    Call Me.InitializeComponent()

    ReDim directory(i)
    For Each dir As DirectoryInfo In (New DirectoryInfo("C:\")).GetDirectories()
        directory(i) = dir
        Me.ComboBox1.Items.Add(directory.Name)
        i += 1
        ReDim Preserve directory(i)
    Next

End Sub

但我认为这样做很痛苦......

于 2013-03-18T05:07:15.773 回答