Files and Folders

Binary file access

Binary access is the most basic way to read a file. It is called binary access because you read the file byte by byte (letter by letter, character by character).

To open a file using Binary Access you simply say For Binary, instead of For Input or Output etc. So,

Open App.Path & "c:\test.txt" For Binary As nFileNum

would open test.txt for binary access. To read characters from a file using binary access, you use the Get statement, which uses the following syntax:

Get FileNumber, ByteNumber, DestinationString

So, you pass the file number that you opened the file with, the byte to start at, and the string to put the result into. You will probably be wondering now how you specify how long a string to get. For binary access, you simply fill DestinationString with x number of spaces, where x is the number of characters you want to retrieve. For example,

sMyString = Space(7)

Get #nFileNum, 12, sMyString

would get 7 characters from the file (because sMyString is filled with 7 spaces), starting at byte 12 (the second parameter of Get). To write to a file using binary access, you use the Get statement:

Get FileNumber, ByteNumber, DestinationString

The following code opens a file for binary access and fills TextBox1 with bytes 12-18 of the file.

Dim nFileNum As Integer, sMyString As String
' Get a free file number
nFileNum = FreeFile

' Open the file test.txt for binary access
Open "test.txt" For Binary As nFileNum

sMyString = Space(7)

' Read 7 characters from the file, starting at byte 12
Get #nFileNum, 12, sMyString

' Close the file
Close nFileNum

' Fill TextBox1 with the string
TextBox1.Text = sMyString

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer lets you make more mistakes faster than any other invention in human history, with the possible exceptions of handguns and tequila” - Mitch Ratcliffe