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
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.
Re: How to create read txt into a string array
E.g.
vb.net Code:
'Get the file content into an array.
Dim lines = IO.File.ReadAllLines(filePath)
'Get the file content into an array, trimming whitespace from each line.
Dim trimmedLines = IO.File.ReadLines(filePath).
Select(Function(line) line.Trim()).
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.