1,102,726 Community Members
yongj
Junior Poster in Training
83 posts since May 2010
Reputation Points: 1 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]

I have a textfile I need to open and I need to put each line into the array. What is the simplest way to add the elements/each line's data into the array while increasing the array as it reads each line? This is blowing my mind right now...

I thought about using a counter and then redim-ing the array (while preserving of course). If so, how would that be constructed? Thanks!

Unhnd_Exception
Deleted Member

I would use a list(Of T)

Heres 2 ways you could do that.

'Add with list(Of T)
Dim fStream As New System.IO.FileStream("c:\text.txt", IO.FileMode.Open)

Dim List As New List(Of String)
Loop

'to go back to an array
Dim thisArray As String() = List.ToArray

fStream.Close()

'with Array
fStream = New System.IO.FileStream("c:\text.txt", IO.FileMode.Open)

Dim sArray As String()
Dim Index As Integer = 0

ReDim Preserve sArray(Index)
Index += 1
Loop

fStream.Close()
sReader.Close()
Unhnd_Exception
Deleted Member

Keep in mind you can use a List(of T) the same way as an array.

'You can use the List(Of T) the same way as an array.
Dim thisLine As String
For i = 0 To List.Count - 1
thisLine = List(i)
Next

For Each S As String In List
thisLine = S
Next

'And if you wanted your array to be 1 based then you could
'get rid of the index.
Dim sArray(0) As String
ReDim Preserve sArray(sArray.Length)
Loop
GeekByChoiCe
Master Poster
701 posts since Jun 2009
Reputation Points: 152 [?]
Q&As Helped to Solve: 170 [?]
Skill Endorsements: 3 [?]
Featured

why not just:

Dim lines() As String = IO.File.ReadAllLines("C:\myFie.txt")
For Each line As String In lines
'do what you want with each single line
Next
You