How to read text file contents for a given file (in four ways)
Posted on July 31, 2011
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | 'Text File Handling - How to read text file contents for a given file (in four ways) '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 |