BinaryReader and BinaryWriter Classes in C#

These classes are used to read and write primitive data types and strings. If you deal only with primitive types, this is the best stream to use. Remember that this data is not easily readable by a human eyeing its contents since the data is read in its binary form.

Table 6.13 lists some of the read and write methods.

ctable-6.13.gif

Table 6.13: Some Methods of the BinaryReader and BinaryWriter Classes

The BinStream class shown in Listing 6.12 is again similar to the StreamRW class from Listing 6.10, with the distinction that the user profile here is stored in binary format.

Listing 6.12: BinaryReader and BinaryWriter Example

using System;
using System.IO;

public class BinStream
{
    public BinStream()
    {
        Writer();
        Reader();
    }

    public static void Main()
    {
        BinStream bs = new BinStream();
        Console.ReadLine();
    }

    private void Writer()
    {
        try
        {
            Console.Out.WriteLine("Preparing to Write ...");

            //Open a FileStream on the file "aboutme"
            FileStream fout = new FileStream("aboutme.txt", FileMode.OpenOrCreate,
            FileAccess.Write, FileShare.ReadWrite);

            //Create a BinaryWriter from the FileStream
            BinaryWriter bw = new BinaryWriter(fout);

            //Create some arbitrary variables
            string name = "Saurabh";
            int age = 20;
            double height = 5.11;
            bool single = true;
            char gender = 'M';

            //Write the values to file
            bw.Write(name);
            bw.Write(age);
            bw.Write(height);
            bw.Write(single);
            bw.Write(gender);

            //Close the file and free resources
            bw.Close();
            Console.WriteLine("Data Written!");
            Console.WriteLine();
        }

        catch (IOException e)
        {
            Console.WriteLine("An IO Exception Occurred :" + e);
        }
    }

    private void Reader()
    {
        try
        {
            Console.WriteLine("Preparing to Read ...");

            //Open a FileStream in Read mode
            FileStream fin = new FileStream("aboutme.txt", FileMode.Open,
            FileAccess.Read, FileShare.ReadWrite);

            //Create a BinaryReader from the FileStream
            BinaryReader br = new BinaryReader(fin);

            //Seek to the start of the file
            br.BaseStream.Seek(0, SeekOrigin.Begin);

            //Read from the file and store the values to the variables
            string name = br.ReadString();
            int age = br.ReadInt32();
            double height = br.ReadDouble();
            bool single = br.ReadBoolean();
            char gender = br.ReadChar();

            //Display the data on the console
            Console.WriteLine("Name :" + name);
            Console.WriteLine("Age :" + age);
            Console.WriteLine("Height :" + height);
            Console.WriteLine("Single? :" + single);
            Console.WriteLine("Gender M/F:" + gender);

            //Close the stream and free the resources
            br.Close();
            Console.WriteLine("Data Read!");
        }

        catch (IOException e)
        {
            Console.WriteLine("An IO Exception Occurred :" + e);
        }
    }
}

outputListitng6.12.gif

Output of above Listing 6.12.

This example has defined a class called BinStream that has two methods: Writer and Reader. The Writer method creates a FileStream object on the file called aboutme.txt and then creates a BinaryWriter from the FileStream object. Then some primitive variables are written to the file using the Write method from the BinaryWriter class. Finally, the BinaryWriter is closed. The Reader method creates a FileStream object on the file previously written (aboutme.txt) in Read mode. A BinaryReader class is instantiated using the FileStream object. The different overloads of the Read method of the BinaryReader class are used to read different primitive data types from the file. Finally, the read values are displayed on the console and the stream is closed.

Conclusion

Hope this article would have helped you in understanding BinaryReader and BinaryWriter Classes in C#. See other articles on the website on .NET and C#.


Similar Articles