devxlogo

Load a text file in one operation

Load a text file in one operation

The fastest way to read a text file is using the Input$ function, as shown in this reusable procedure:

Function FileText (filename$) As String    Dim handle As Integer    handle = FreeFile    Open filename$ For Input As #handle    FileText = Input$(LOF(handle), handle)    Close #handleEnd Function

This method is much faster than reading each single line of the file using a Line Input statements. Here’s how you can load a multiline textbox control with the contents of Autoexec.bat:

Text1.Text = FileText("c:autoexec.bat")

UPDATE: Andrew Marshall wrote us to point out that the above routine fails when the file includes a Ctrl-Z (EOF) character, so we prepared a better version that works around that problem:

Function FileText(ByVal filename As String) As String    Dim handle As Integer        ' ensure that the file exists    If Len(Dir$(filename)) = 0 Then        Err.Raise 53   ' File not found    End If        ' open in binary mode    handle = FreeFile    Open filename$ For Binary As #handle    ' read the string and close the file    FileText = Space$(LOF(handle))    Get #handle, , FileText    Close #handleEnd Function

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