C# program to demonstrate the BinaryReader and BinaryWriter classes

Here, we are going to learn about the BinaryReader and BinaryWriter classes and demonstrating the example of BinaryReader and BinaryWriter classes.
Submitted by Nidhi, on September 21, 2020

Here we will create a file using FileStream class and write data using BinaryWriter class and then read data from the file using BinaryReader class and print data on the console screen.

Program:

The source code to demonstrate the BinaryReader and BinarayWriter class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the BinaryReader class.

using System;
using System.IO;

class Demo
{
    const string fileName = "sample.txt";

    public static void WriteData()
    {
        FileStream file = File.Open(fileName, FileMode.Create);

        using (BinaryWriter bwriter = new BinaryWriter(file))
        {
            bwriter.Write(108);
            bwriter.Write(@"Hello World");
        }
    }
    public static void PrintData()
    {
        int     luckyNum=0  ;
        string  str     ="" ;

        FileStream file = File.Open(fileName, FileMode.Open);
        using (BinaryReader breader = new BinaryReader(file))
        {
            luckyNum = breader.ReadInt32();
            str      = breader.ReadString();
        }
        Console.WriteLine("Lucky Number : " + luckyNum);
        Console.WriteLine("String       : " + str     );
        
    }

    static void Main()
    {
        WriteData();
        PrintData();
    }
}

Output:

Lucky Number : 108
String       : Hello World
Press any key to continue . . .

Explanation:

Here, we created a class Demo that contains three static methods WriteData(), PrintData(), and Main().

In the WriteData() method, we created the file "Sample.txt" and write data (lucky number and hello world message) into the file using BinaryWriter class.

In the PrintData() method, we read the data from the "Sample.txt" file and print it on the console screen.

The Main() method is the entry point for the program, here we call both WriteData() and PrintData() methods.





Comments and Discussions




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.