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

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 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.