Q:

C# program to demonstrate the BinaryReader and BinaryWriter classes

belongs to collection: C# Files Programs

0

C# program to demonstrate the BinaryReader and BinaryWriter classes

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to compare the content of two files usi... >>
<< C# program to get the size of a specified folder i...