Custom Search

Friday, November 28, 2008

Convert a file to an array

Private Function FileToArray(ByVal strFileName As String) As String()

On Error GoTo Hell

'Convert any file to an array of text strings
'Split by vbCrLf's

Dim strEntireFile As String
Dim FileNum As Integer

'Set the inital array size
Dim retArray() As String

' Make sure exists
If (Dir(strFileName) = "") Then Exit Function

' Open file | Read all in
FileNum = FreeFile
Open strFileName For Binary Access Read As #FileNum

' Get whole file
strEntireFile = String(LOF(FileNum), 0)
Get #FileNum, , strEntireFile

' Close
Close #FileNum

' Remove the vbcrlf's at the end
Do Until (Right$(strEntireFile, 2) <> vbCrLf)
' Shorten by 2
strEntireFile = Mid$(strEntireFile, 1, Len(strEntireFile) - 2)
Loop

' Split by crlfs
retArray = Split(strEntireFile, vbCrLf)

'Return the array
FileToArray = retArray

Exit Function

Hell:

' Return this
ReDim FileToArray(0)

End Function

No comments: