devxlogo

FileToArray – Reading all lines from a text file into a String array

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:	est.txt")'   Dim line As String'   For Each line In lines'       Debug.WriteLine(line)'   NextFunction 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, "
")    Finally        If Not sr Is Nothing Then sr.Close()    End TryEnd Function

See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist