Read Text File into string VB6

This article is written by Pon Saravanan  on 04-Jul-07 Last modified on :06-Aug-10

VB6 Read Text File

With this artcle, I am going to explain various ways we can Read Text File into a string variable using Classic VisualBasic.

The first and easy way to acess a txt file is using the simple open method available in VB. For this method, we need to allocate a unique file number for opening. And the same number should be used to close.

There are various modes to open some of them are Append, Binary, Input, Output, or Random. by default Random will be used.

In this code I have closed the connection after error has been handled(or intended to be handled). This close method  will not do anything if the file number is not used to open. so it is safe even error has been occured before opening.

Using FileSystemObject in VB6 Read Text File

With FileSystemObject File IO operations are very easier in VB. Almost all the required functions are well defined. For reading, we have to use OpenTextFile method in the FileSystemObject. Once opened, A TextStream object can be used to fetch the data. To fetch line by line we need to loop through until we reach EOF. To find the EOF, FileSystemObject has a property AtEndOfStream. When it is true, it represents that the end of file is reached.

Private Function ReadTextFile(strPath as String)as String
 Dim fso As New FileSystemObject
 Dim ts As TextStream       
 Dim strOutput as String
 Set ts = fso.OpenTextFile(strPath)
 Do until ts.AtEndOfStream
  strOutput = strOutput + ts.ReadLine
 ReadTextFile = strOutput
End Sub

The above code needs file system object to be referenced to Read Text File

Using the Open method in Classic VB

Using a open method is much easier and effective way to Read Text File. It is well supported from a earlier versions of the visual basic.  Because of it's simplicity, we can see this in a lot of applications. Once file is opened please close it immediately after done working with the whole text fetched. This open method is working based on FileNumber. So the same FileNumber has to be used to close aswell.

Private Sub Command1_Click()
MsgBox Text2String("c:\Test.txt")
End Sub
Public Function Text2String(strPath As String) As String
    On Error GoTo ErrTrap
    Dim intFileNumber As Integer
    If Dir(strPath) = "" Then Exit Function
    intFileNumber = FreeFile
    Open strPath For Input As #intFileNumber
    Text2String = Input(LOF(intFileNumber), #intFileNumber)
    Close #intFileNumber
End Function

Search using Regular Expressions(RegEx)

If search string is not specified the function will give the entire content. If the search string is specified then the search results will be appended to a text and will be returned. The search is regular expression based search

Since the search is regular expression based, the regular expression should be validated before using the function. Or else the function will be hanging due to invalid regular expression.

Public Function Text2String(ByVal strPath As String, _
                            Optional ByVal strSearch As String, _
                            Optional ByVal CompareMode As VbCompareMethod _
                            ) As String
    Dim strBuff As String
    Dim strContent As String
    Dim rxSearch As New RegExp
    Dim rxMatches As MatchCollection
    Dim rxMatch As Match
    Dim strOutput As String
    On Error GoTo ErrTrap
    rxSearch.IgnoreCase = (CompareMode = vbTextCompare)
    rxSearch.Global = True
    rxSearch.MultiLine = True
    rxSearch.Pattern = strSearch
    Open strPath For Binary As #1
    strBuff = Space(LOF(1))
    Get #1, , strBuff
    If strSearch = vbNullString Then
        strOutput = strBuff
        Set rxMatches = rxSearch.Execute(strBuff)
        For Each rxMatch In rxMatches
            strOutput = strOutput & rxMatch.Value
    End If
    Text2String = strOutput
    Close #1 ' close the connection before proceeding to the next step
   If Err Then Err.Raise Err.Number, , "Error from Functions.Text2String " & Err.Description
End Function


This function can be used as follows to VB6 Read Text File

MsgBox Text2String("c:/boot.ini")
MsgBox Text2String("c:/boot.ini", "timeout.*")

    Very nice and detailed article on reading a text file i ever read.
    Thank you,
    1/5/2011 5:58:52 AM

    "The above code needs file system object to be referenced"

    Can you be a little more specific as to what reference needs to be added to the VB project?
    1/2/2010 3:38:34 PM

    You need to reference 'Scripting Runtime' for accessing file system object 1/2/2010 9:56:14 PM

    i want to know if how to compute minutes in notepad using vb 6.0? 7/22/2010 2:02:27 AM

  • pons
    Can you please describe a bit more for me to understand. Thanks 7/22/2010 2:13:43 AM

    Code works fine to read a text file but no line break and carriage return ignored. How to over come this problem? 9/4/2011 10:49:16 PM

Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    

Spam Bot Trap


Select Theme