FileToArray - Reading all lines from a text file into a String array
' Read all lines from a text file into a String array
'
' Example:
' Dim lines As String() = FileToArray("D:\test.txt")
' Dim line As String
' For Each line In lines
' Debug.WriteLine(line)
' Next
Function FileToArray(ByVal filePath As String) As String()
Dim content As String
Dim lines As New ArrayList
Dim sr As System.IO.StreamReader
' read the file's lines into an ArrayList
Try
sr = New System.IO.StreamReader(filePath)
Do While sr.Peek() >= 0
lines.Add(sr.ReadLine())
Loop
Finally
If Not sr Is Nothing Then sr.Close()
End Try
' convert from ArrayList to a String array
Return CType(lines.ToArray(GetType(String)), String())
End Function
' If the input file is relatively small, 2-5 MB, you can use this simpler and
' faster version:
Function FileToArray(ByVal filePath As String) As String()
Dim sr As System.IO.StreamReader
Try
sr = New System.IO.StreamReader(filePath)
Return System.Text.RegularExpressions.Regex.Split(sr.ReadToEnd, "\r\n")
Finally
If Not sr Is Nothing Then sr.Close()
End Try
End Function