How to load .csv file into an array.

Peter Hibbs 101 Reputation points
2021-04-05T09:40:06.917+00:00

Hi,

VB.NET 2019

I am trying to load a comma delimited .csv file on disk into a string array. I have found the code below which works OK but the problem is that I want to be able to access the array from any part of the program which does not work. I am guessing that I need to declare the variable vArray as a Public (or whatever) variable at the top of the form code window but the code below uses Dim vArray which does not allow this. How can I change the code to copy the data into the array without using the Dim statement?

Function FetchNewWord() As String

            'Fetch new word from list of words

            Dim vFilename As String

            vFilename = "C:\VSI 2019\My Game\Words4.csv"
            Dim vArray As String() = System.IO.File.ReadAllLines(vFilename)
            Return vArray(1)
End Function

Peter Hibbs.

Developer technologies Windows Forms
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2021-04-05T10:06:22.87+00:00

    This function returns the second line of the .csv (vArray(1))

    To get all the file, you coud just do :

    Public vArray As String()  
    

    then

     Dim vFilename As String = "C:\VSI 2019\My Game\Words4.csv"  
     vArray = System.IO.File.ReadAllLines(vFilename)  
    

    (and for .CSV files, it is better to use TextFieldParser Classr)


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.