1.11M Members

Open Textfile and read lines into array

 
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
 
0
 

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
            List.Add(sReader.ReadLine)
        Loop

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

        fStream.Close()
        sReader.Close()


        '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
        Loop

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

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
        Do While sReader.Peek >= 0
            ReDim Preserve sArray(sArray.Length)
            sArray(UBound(sArray)) = sReader.ReadLine
        Loop
 
0
 

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
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: