vb.net

Reading from text file to array


I am trying to read a text file in line by line and add it to an array, current code and output are below. How would I read it in properly, i.e. get the actual text to read into the array, rather than the current output. (Console App version of VB.NET)

Code:

Sub Main()
    Dim file As String = "C:\path\to\file\textfile.txt"
    Dim quoteArray As New ArrayList
    FileOpen(1, file, OpenMode.Input)
    Do While Not EOF(1)
        quoteArray.Add(LineInput(1))
    Loop
    FileClose(1)
    Console.WriteLine(quoteArray)
    Console.ReadLine()
End Sub

Output:

System.Collections.ArrayList

Solution

  • Your code works, but you cannot print an entire array at once. You've got to iterate the array somehow and print each item separately or combine them into a single string.

    Printing each item separately:

    For Each Item As String In quoteArray
        Console.WriteLine(Item)
    Next
    

    Combining them to a single string using String.Join():

    Console.WriteLine(String.Join(Environment.NewLine, quoteArray.ToArray(GetType(String))))
    

    However what I don't understand is why you are writing in VB.NET, but are still using outdated functions and classes from the VB6 era:

    There are much better alternatives these days:

    Or you can replace all the above with a regular array and a single call to File.ReadAllLines().

    1. StreamReader solution:

      Dim quoteList As New List(Of String)
      
      Using Reader As New StreamReader("C:\path\to\file\textfile.txt")
          While Reader.EndOfStream = False
              quoteList.Add(Reader.ReadLine())
          End While
      End Using
      
    2. File.ReadAllLines() solution:

      Dim quoteArray As String() = File.ReadAllLines("C:\path\to\file\textfile.txt")
      

    Printing the list/array using a loop:

    For Each Item As String In quoteArray
        Console.WriteLine(Item)
    Next
    

    Printing the list/array using String.Join():

    Console.WriteLine(String.Join(Environment.NewLine, quoteArray))
    

    (if you are using the quoteList solution just replace quoteArray with quoteList in these two examples)