无法让数组工作

时间:2014-03-23 17:37:30

标签: arrays vb.net visual-studio-2012

我想要做的是从目录中获取所有文件名,并将它们输入到一维字符串Array中的单独索引中。下面的代码应该有用,我不明白我哪里出错了?

Public Sub RetrieveFilesAndPutinArray()
    'Will be processed when Finish button is pressed.
    '
    Dim strArr As String() = Nothing ''Array <- i suspect declared the array                   wrong or something
    Dim indexCounter = 0

    'For each file:
    For Each foundFile As String In My.Computer.FileSystem.GetFiles(
    My.Computer.FileSystem.SpecialDirectories.MyDocuments)
        'Add the file path and file name to the index position which is determined by:         "IndexCounter"
        strArr(indexCounter) = foundFile 'Array index is populated with string text of ^

        'Then increment the index number by 1
        indexCounter = indexCounter + 1

    Next 'Repeat until all files have been processed.

    For Count = 1 To (strArr.Length() - 1)
        'Loop through all the files in the strArr Array and popup a msg box with the contents of the index number "Count"
        MsgBox(strArr(Count))
    Next

    'Procedure complete.
    'Can u see anything wrong? theoretically it should work now... how about asking StackOverflow.. get a quick resoponse.. should be

End Sub

1 个答案:

答案 0 :(得分:1)

首先你必须Redim你的数组,然后你必须从0迭代到strArr.Length() - 1

 Public Sub RetrieveFilesAndPutinArray()
        'Will be processed when Finish button is pressed.
        '
        Dim strArr As String() = Nothing  '' New String() ''Array <- i suspect declared the array                   wrong or something

        Dim indexCounter = 0

        Dim count As Integer = My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments).Count

        ReDim strArr(count - 1)
        'For each file:
        For Each foundFile As String In My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
            'Add the file path and file name to the index position which is determined by:         "IndexCounter"
            strArr(indexCounter) = foundFile 'Array index is populated with string text of ^

            'Then increment the index number by 1
            indexCounter = indexCounter + 1

        Next 'Repeat until all files have been processed.

        For count = 0 To (strArr.Length() - 1)
            'Loop through all the files in the strArr Array and popup a msg box with the contents of the index number "Count"
            MsgBox(strArr(count))
        Next

        'Procedure complete.
        'Can u see anything wrong? theoretically it should work now... how about asking StackOverflow.. get a quick resoponse.. should be

    End Sub

P.S您可以优化此代码