Sunday, November 9, 2008

Read and Display from a Binary File. VB.NET

Hi,
Here i like to explain how simple is to read and display a binary file using VB.net. Actually the first thing made me to post this was first i ran into trouble when reading from a binary file.

Here what i am going to do is read from a binary file which has the following format;
Int,Int,Double


so lets look at the code :)

Try
'opening the file stream
Dim transfs As New FileStream("C:\Temp\TRANS.DAT", FileMode.Open)
Dim transRdr As New BinaryReader(transfs)
Dim i As Integer = 1
Dim len As Long = transfs.Length()
transRdr.BaseStream.Position = 0

While transRdr.BaseStream.Position < len

transaction = transRdr.ReadInt32
custcode = transRdr.ReadInt32
amount = transRdr.ReadDouble
'appending the result to a text box
frmtran.txtTransactions.AppendText(transaction.ToString() & ", " & custcode.ToString() & ", " & amount.ToString() & Environment.NewLine())
'Display the transactions form
End While
transfs.Close()
transRdr.Close()

frmtran.ShowDialog()

Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try


Notice that i used position to read from the binary file
That's all fokes see how easy it is

Happy Coding.

No comments: