Connecting Tech Pros Worldwide Forums | Help | Site Map

How to read a file in VB - Part 2 - VB6, Binary mode (Get)

Moderator
 
Join Date: Oct 2006
Location: Australia
Posts: 7,748
#1   May 18 '07
Here is a very simple example routine which reads a file from disk, in one big lump. This uses the built-in VB statements only. Later we will cover the FileSystemObject, which provides greater functionality at the expense of slightly greater code complexity.

This self-contained routine can be pasted into a code module and called from anywhere, including the immediate window. It will expect you to pass the name of a file (including the path if it isn't in the current directory) and will copy the contents of the file to the immediate window. Note it will also avoid, as far as possible, interfering with any other processing which may be going on at the time.

The extra parameter (compared to the prior sample in this series) allows you to request that the file contents be dumped as one big string (appropriate for a text file) or byte by byte (appropriate for most other file types).

Expand|Select|Wrap|Line Numbers
  1. Public Sub DumpFile_V02(ByVal FileName As String, ByVal TreatAsText As Boolean)
  2.   Dim FileNo As Long
  3.   Dim FileSize As Long
  4.   Dim Buffer As String
  5.   Dim CharNo As Long, Char As String * 1
  6.  
  7.   FileNo = FreeFile ' Get next available file number.
  8.   Open FileName For Binary Access Read Shared As #FileNo
  9.   FileSize = LOF(FileNo) ' Determine how large the file is (in bytes).
  10.   Buffer = Space$(FileSize) ' Set our buffer (string) to that length.
  11.  
  12.   ' The length of the string (Buffer) determines how many bytes are read...
  13.   Get #FileNo, , Buffer ' Grab a chunk of data from the file.
  14.   Close #FileNo
  15.  
  16.   ' Display the results, either as one big chunk or byte-by-byte.
  17.   If TreatAsText Then
  18.     Debug.Print Buffer
  19.   Else
  20.     For CharNo = 1 To FileSize
  21.       Char = Mid(Buffer, CharNo, 1)
  22.       Debug.Print Format(CharNo, "#,###"); " = Decimal(" _
  23.           ; Format(Asc(Char), "000"); ")  Hexadecimal(" _
  24.           ; Hex$(Asc(Char)); ")  ["; Char; "]"
  25.       DoEvents
  26.     Next
  27.     Beep ' Just let the user know we're finished.
  28.   End If
  29. End Sub

Last edited by Killer42; Jan 16 '08 at 08:17 AM.



Closed Thread