Friday, January 20, 2012

BinaryReader and BinaryWriter in .Net (C#)


BinaryReader and BinaryWriter classes are available in System.IO namespace. BinaryReader and BinaryWriter classes are used to write primitive data types to file (primitive data types like int, decimal, float, double, long, short etc.). It also allows us to write strings and array of primitive data types along with primitive data types. The data stored inside file is not human readable because it’s stored in binary format. To store data in normal text you can use StreadReader and StreamWirter class instead. Please go through StreamReader and StreamWriter article for more information.


Read/Write text to file using BinaryReader and BinaryWriter

//writes data to test.bin file using binarywriter
using (BinaryWriter bw = new BinaryWriter(new FileStream(@"d:\Temp\test.bin", FileMode.Create)))
{
    for (int i = 0; i < 5; i++)
    {
        bw.Write(i);
    }
}

//reads data from test.bin file using binaryreader
using (BinaryReader br = new BinaryReader(new FileStream(@"d:\Temp\test.bin", FileMode.Open)))
{
    for (int i = 0; i < 5; i++)
    {
        br.ReadInt32();
    }
}

Output –

No comments:

Post a Comment