question

PeterHibbs-9836 avatar image
0 Votes"
PeterHibbs-9836 asked PeterHibbs-9836 commented

How to load .csv file into an array.

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.

windows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered PeterHibbs-9836 commented

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)



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

OK, thanks, that works well.

I will look into the TextFieldParser Class to see what that does.

I know that vArray(1) returns the second line but I am intending to replace the 1 with a random number depending on the size of the array. I just need to find how to determine the number of elements in the returned array and choose a number between 0 and the highest number in VB.NET.

Peter.

0 Votes 0 ·