Read/Write binary data
Imports System.IO
 Public Class RWByte
   Public fs As filestream
   Public Buffer(10) As Byte
   Public Sub Main()
      Dim fn As String = "test.xxx"
      Dim start, count As Integer
      start = 0
      Dim buff() As Byte = {55, 22, 255, 126, 18} ' Data to write
      count = buff.Length ' the number of bytes to write
      fs = New FileStream(fn, FileMode.Create) ' Open file
      fs.Write(buff, 0, 5) ' write 5 bytes of array starting at index zero 
      fs.Close() ' close Write stream
      fs = New FileStream(fn, FileMode.Open) ' open stream for read
      fs.Read(Buffer, start, count) ' read file into different buffer
      fs.Close() ' close read stream
   End Sub
End Class

 

Open for Read or Write with the constructor and the appropriate FileMode enumeration. The Write or Read operation passes in the byte array, the index to start and the number of bytes. The Read operation returns the amount of bytes read, which could be less than the count passed in to the Read method.

Reading and writing an array of bytes is one of the most useful activities for a programmer. Why? Because you can open and read any file, such as a waves, mp3's or midi files. Of course you have to be able to decode the file. Often the format of a binary file is defined somewhere on the internet.

Its a challenge to understand binary files, but the power it give you as a programmer is incredible. See the BitConverter link above showing how to access a .wav file, for an example.


10/11/2015
TheLonelyProgrammer.Net
Alone in a sea of non-programmers
Home Bit Converter Write/Read Bytes