C# - BinaryReader and BinaryWriter Classes Example

Learn about the BinaryReader and BinaryWriter classes and demonstrating the example of BinaryReader and BinaryWriter classes. By Nidhi Last updated : April 03, 2023

BinaryReader and BinaryWriter Classes Example

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.

C# program to demonstrate the BinaryReader and BinaryWriter classes

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.

C# Files Programs »


Comments and Discussions!

Load comments ↻






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