user3325388
user3325388

Reputation: 3

can't get array to work

What i'm trying to do is get all the file names from a directory and input them into a separate index in a one-dimensional string Array. The code below should work, I don't understand where i've gone wrong?

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

Upvotes: 0

Views: 62

Answers (1)

Sargis Koshkaryan
Sargis Koshkaryan

Reputation: 1030

At first you must Redim your array, then you must iterate from 0 to 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 you can optimize this code

Upvotes: 1

Related Questions