How to Read the contents of an entire file into memory and be able to READ it

Posted on 2007-12-04
Last Modified: 2011-04-14
I have a need to quickly read the contents of a file into memory using VB6.  I know how to do this in VB.NET via BinaryReader functionality; however, I need to do this within VB6.

I have used the following code that can read the data from a file into memory, but I don't know know how to *access* it:

hMem = GlobalAlloc(GPTR, FSize)
If hMem <> 0 Then
            lpMem = GlobalLock(hMem)
            hFile = OpenFile(InpFile, fileStruct, OF_READ Or _

             BytesRead = hread(hFile, ByVal lpMem, FSize)

That's fine and dandy, but how do I parse the data in memory location lpMem into a string array?  i.e. in C one might say:

char x[100000]
x[1] = lpMem + 1

but how do you do this in VB6?????

I've attached a code snippet of some sample code I found on the net.

Thanks in advance for your help
Dim InpFile As String
      Dim OutFile As String
      Dim hFile As Long
      Dim fileStruct As OFSTRUCT
      Dim FSize As Long
      Dim BytesRead As Long
      Dim BytesWritten As Long
      Dim hMem As Long
      Dim lpMem As Long
      Dim r As Long
      Dim bts As Byte
      InpFile = "input.txt"
      OutFile = "OUTPUT.txt"
      'Get the size of the file to be read
      FSize = FileLen(InpFile)
      If FSize > 0 Then
         'Allocate a block of memory equal to the size of the input file.
         'hMem = GlobalAlloc(GMEM_ZEROINIT, FSize)
         hMem = GlobalAlloc(GPTR, FSize)
         If hMem <> 0 Then
            lpMem = GlobalLock(hMem)
            'Read the file into memory
            hFile = OpenFile(InpFile, fileStruct, OF_READ Or _
            BytesRead = hread(hFile, ByVal lpMem, FSize)
            MsgBox Format(BytesRead) & " bytes read into memory"
            r = lclose(hFile)
            'Write the file back to disk to verify the file was
            'read correctly
            hFile = OpenFile(OutFile, fileStruct, OF_CREATE Or _
                             OF_WRITE Or OF_SHARE_DENY_NONE)
            BytesWritten = hwrite(hFile, ByVal lpMem, FSize)
            MsgBox Format(BytesWritten) & " bytes written to output file"
            r = lclose(hFile)
            'Free resources
            r = GlobalUnlock(hMem)
            r = GlobalFree(hMem)
             MsgBox "Not enough memory to store file"
         End If
         MsgBox "Input file is zero bytes in length"
      End If

Open in new window

Question by:richelieu7777
LVL 81

Accepted Solution

zorvek (Kevin Jones) earned 500 total points
ID: 20404111
The sample code below illustrates how to use the Visual Basic file system to read an entire file into a string variable.

   Dim FilePath As String
   Dim FileNumber As Long
   Dim FileData As String

   FilePath = "C:\Full\Path\To\File.txt"
   FileNumber = FreeFile
   Open FilePath For Binary Access Read As FileNumber
   ' Use following if non-unicode data
   FileData = StrConv(InputB(LOF(FileNumber), FileNumber), vbUnicode)
   ' Use following if unicode data
   'FileData = InputB(LOF(FileNumber), FileNumber)
   Close FileNumber

LVL 17

Expert Comment

by:Shanmuga Sundaram
ID: 20404172
if you want to read and write text file please check this

Private Sub readandwritefile()
On Error GoTo errfound
Dim InpFile As String
      Dim OutFile As String
      InpFile = "c:input.txt"
      OutFile = "c:\OUTPUT.txt"
Dim filecontent As String
Open InpFile For Input As #1
filecontent = Input$(LOF(1), 1)
Close #1
Open OutFile For Output As #2
Print #2, filecontent
Close #2
Exit Sub
MsgBox "Error " & Err.Description
End Sub

Private Sub Form_Load()
End Sub
LVL 38

Expert Comment

ID: 20404203
Function that returns a byte array, given the path:

Public Function fGetFileContentBytes(strPath As String) As Byte()
    Dim hFile As Integer
    Dim bytFileContent() As Byte
    If Len(Dir(strPath)) = 0 Then Exit Function
    On Error GoTo errGetFile
    'Handle zero length files
    If FileLen(strPath) = 0 Then
        ReDim bytFileContent(-1 To -1)
        hFile = FreeFile
        Open strPath For Binary As #hFile
        ReDim bytFileContent(1 To LOF(hFile))
        Get #hFile, , bytFileContent
        Close #hFile
    End If
    fGetFileContentBytes = bytFileContent
    Exit Function
    MsgBox Err.Description, vbCritical, "GetFileContentBytes"
End Function
LVL 45

Expert Comment

ID: 20411417
Dim strFilePath As String
Dim intFN As Integer
Dim strFileData As String
Dim colFileData As New Collection
Dim lngEOL_Posn As Long
Dim lngSOL_Posn As Long

strFilePath = "C:\Full\Path\To\File.txt"
intFN = FreeFile
Open FilePath For Input As intFN
strFileData = Input(LOF(intFN), intFN)
Close intFN
'parse the data
lngSOL_Posn = 1
lngEOL_Posn = InStr(lngSOL_Posn, strFileData, vbCrLf)
Do Until lngEOL_Posn = 0
  colFileData.Add Mid$(strFileData, lngSOL_Posn, lngEOL_Posn - lngSOL_Posn)
  lngSOL_Posn = lngEOL_Posn +2
  lngEOL_Posn = InStr(lngSOL_Posn, strFileData, vbCrLf)
'Add the last segment
If lngSOL_Posn < Len(strFileData) Then _
colFileData.Add Mid$(strFileData, lngSOL_Posn)
strFileData = vbNullString

At this point, each line of the file is an item in the collection.  You can reference the collection items numerically, just as you would a string array.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question