Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: beginner
Dec 1, 2003

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
Marco Bellinaso
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap