Results 1 to 3 of 3

Thread: How to create read txt into a string array

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2018
    Posts
    12

    Talking How to create read txt into a string array

    I want to read it line by line. If there is 10 lines, then the array should be size = 10

    I have the following code, but I do not know how to NOT preset the array size

    Code:
        Public Function MyReadLine(ByVal FileLoc As String) As String
            Dim AllText As String = "", LineOfText As String = ""
            Dim StreamToDisplay As StreamReader
            StreamToDisplay = My.Computer.FileSystem.OpenTextFileReader(FileLoc)
            Do Until StreamToDisplay.EndOfStream 'read lines from file  
                LineOfText = StreamToDisplay.ReadLine()
                AllText = AllText & LineOfText & vbCrLf
            Loop
            Return AllText 'display file   
        End Function

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,008

    Re: How to create read txt into a string array

    If you simply want an array containing the lines of a file then call IO.File.ReadAllLines. If you want to process the lines of a file as you read them then call IO.File.ReadLines.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,008

    Re: How to create read txt into a string array

    E.g.
    vb.net Code:
    1. 'Get the file content into an array.
    2. Dim lines = IO.File.ReadAllLines(filePath)
    3.  
    4. 'Get the file content into an array, trimming whitespace from each line.
    5. Dim trimmedLines = IO.File.ReadLines(filePath).
    6.                            Select(Function(line) line.Trim()).
    7.                            ToArray()
    You could call ReadAllLines instead of ReadLines in the second case but ReadLines is more efficient because it doesn't create a full array of the original data that you don't use afterwards. If you did call ReadAllLines in that case then there would be two arrays at the end when you only need one. ReadLines discards each line after it is read and processed.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width