Home > How-To Library > Text File Handling
How to read text file contents for a given file (in four ways)
**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * **************************************************************** 'Using Non-FSO: Public Function ReadTextFileContents(filename As String) As String Dim fnum As Integer, isOpen As Boolean On Error GoTo Error_Handler ' Get the next free file number. fnum = FreeFile() Open filename For Input As #fnum ' If execution flow got here, the file has been open without error. isOpen = True ' Read the entire contents in one single operation. ReadTextFileContents = Input(LOF(fnum), fnum) ' Intentionally flow into the error handler to close the file. Error_Handler: ' Raise the error (if any), but first close the file. If isOpen Then Close #fnum If Err Then Err.Raise Err.Number, , Err.Description End Function ' Load a text file into a TextBox control. Text1.Text = ReadTextFileContents("c:\bootlog.txt") 'Using FSO: 'Set a reference to "Microsoft Scripting Runtime" Public Function ReadTextFileContentUsingFSO(ByVal sFileName As String) As String Dim fs As FileSystemObject Dim ts As TextStream Dim strText As String Set fs = New FileSystemObject 'To Read If fs.FileExists(sFileName) Then Set ts = fs.OpenTextFile(sFileName) Do While Not ts.AtEndOfStream strText = strText & ts.ReadLine & vbCrLf Loop ts.Close End If ReadTextFileContent = strText Set ts = Nothing Set fs = Nothing End Function 'Using Binary mode: Public Function ReadTextFileContentUsingBinaryMode(ByVal sFileName As String) As String Dim handle As Integer ' ensure that the file exists If Len(Dir$(sFileName)) = 0 Then Err.Raise 53 ' File not found End If ' open in binary mode handle = FreeFile Open sFileName$ For Binary As #handle ' read the string and close the file ReadTextFileContentUsingBinaryMode = Space$(LOF(handle)) Get #handle, , ReadTextFileContentUsingBinaryMode Close #handle End Function 'Fastest way if you are dealing with large text files Public Function TextFromFile(ByVal fInStream As String) As String 'Returns text in file fInStream 'Example usage: Debug.Print TextFromFile ("C:\WINDOWS\Programs.txt") 'This is extremely fast, especially if you are dealing with large text files. On Error GoTo TextFromFile_Error Dim I As Long I = FreeFile Open fInStream For Input Lock Write As #I Screen.MousePointer = vbHourglass DoEvents TextFromFile = StrConv(InputB$(LOF(I), I), vbUnicode) On Error GoTo 0 TextFromFile_Error: Close #I Screen.MousePointer = vbDefault End Function
If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.