Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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:

 

   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 can't seem to get the right syntax. Please help.

Posted

Remove the For Loop, and this code should do the job:

 

 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, that's why only the last entry was saved.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...