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!

Recommended Answers

All 3 Replies

Member Avatar

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 sReader As New System.IO.StreamReader(fStream)

        Dim List As New List(Of String)
        Do While sReader.Peek >= 0

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


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

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

        Do While sReader.Peek >= 0
            ReDim Preserve sArray(Index)
            sArray(Index) = sReader.ReadLine
            Index += 1

Member Avatar

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)

        For Each S As String In List
            thisLine = S

        'And if you wanted your array to be 1 based then you could
        'get rid of the index.
        Dim sArray(0) As String
        Do While sReader.Peek >= 0
            ReDim Preserve sArray(sArray.Length)
            sArray(UBound(sArray)) = sReader.ReadLine

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.