VB.Net program to demonstrate the BinaryReader and BinaryWriter class

Here, we are going to demonstrate the BinaryReader and BinaryWriter class in VB.Net.
Submitted by Nidhi, on January 08, 2021 [Last updated : March 08, 2023]

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("All the best")

        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)

        End Sub
    End Class

    Sub Main()
        Dim S As New Sample()

    End Sub
End Module


Lucky Number : 108
String       : All the best
Press any key to continue . . .


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 »

All VB.Net Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.