Home »
VB.Net »
VB.Net Programs
VB.Net program to demonstrate the BinaryReader and BinaryWriter class
By Nidhi Last Updated : November 11, 2024
BinaryReader and BinaryWriter Class Example in VB.Net
Here, we will write and read data into a text file using BinaryWriter and BinaryReader class.
Program/Source Code:
The source code to demonstrate the BinaryReader and BinaryWriter class is given below. The given program is compiled and executed successfully.
VB.Net code to demonstrate the example of BinaryReader and BinaryWriter class
'Vb.Net program to demonstrate the
'BinaryReader and BinaryWriter class.
Imports System.IO
Module Module1
Class Sample
Private fileName As String = "sample.txt"
Public Sub WriteData()
Dim f As FileStream = File.Open(fileName, FileMode.Create)
Dim bwriter As New BinaryWriter(f)
bwriter.Write(108)
bwriter.Write("All the best")
f.Close()
End Sub
Public Sub PrintData()
Dim luckyNum As Integer = 0
Dim msg As String = ""
Dim f As FileStream = File.Open(fileName, FileMode.Open)
Dim breader As New BinaryReader(f)
luckyNum = breader.ReadInt32()
msg = breader.ReadString()
Console.WriteLine("Lucky Number : " & luckyNum)
Console.WriteLine("String : " & msg)
f.Close()
End Sub
End Class
Sub Main()
Dim S As New Sample()
S.WriteData()
S.PrintData()
End Sub
End Module
Output
Lucky Number : 108
String : All the best
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains a class Sample and a Main() function. The Sample class contains a data member filename, that contains the name of the file to perform read and write operation.
The Sample also contains two method WriteData() and PrintData(). The WriteData() method is used to write data into a text file using the BinaryWriter class. The PrintData() method is used to read the data from a text file using BinaryReader class and print the data on the console screen.
VB.Net BinaryReader and BinaryWriter Programs »