Syntax HELP: Array/CSV Split

uppaclazzthugz9

New member
Joined
Apr 1, 2004
Messages
1
I basically need to read a CSV text file with multiple entries that looks like such:

Smith,John,(111)-111-1111
Michaels,Gary,(222)-222-2222
Jones,Bill,(333)-333-3333


I am then trying to store the names in a memberData array and the phone #s in a phoneData array respectively. Below is the code in which I have so far:

Code:
    Dim fileName, line, Message As String
    Dim temp As String()
    Dim memberData() As String = {}
    Dim phoneData() As String = {}
    Dim i, counter, upperBound As Integer

    Dim sr As IO.StreamReader

    -----------------------------------------

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

        fileName = "Members.txt"
        counter = 0
        upperBound = 0

        If IO.File.Exists(fileName) Then
            sr = IO.File.OpenText(fileName)
        Else
            Message = "Either no file has yet been created or the file "
            Message &= fileName & " is not where expected."
            MsgBox(Message, , "File Not Found")
        End If

        For i = 0 To 4
            Do While (sr.Peek() <> -1)
                line = sr.ReadLine
                temp = line.Split(","c)
                ReDim Preserve memberData(i)
                memberData(i) = temp(0) & "," & temp(1)
            Loop
        Next

        lstNames.Items.Add(memberData(0))
        sr.Close()
    End Sub

The problem I am running into is that the temp array locations 0 and 1 keep getting overwritten and the last entry in the text file is just being stored instead of all the entries. I have been going at this for a while and cant seem to get the right syntax. Please help.
 
Remove the For Loop, and this code should do the job:

Code:
  i=0
  Do While (sr.Peek() <> -1)
    line = sr.ReadLine
    temp = line.Split(",")
    ReDim Preserve memberData(i)
    ReDim Preserve phoneData(i)
    memberData(i) = temp(0) & "," & temp(1)
    phoneData(i) = temp(2)
    i += 1
  Loop

The way you had it, the counter was increased only after you finished reading all the lines, thats why only the last entry was saved.
 
Back
Top