How to: Read and Write Binary file in C#

In this article we will see how to use BinaryReader and BinaryWriter class for reading and writing binary files respectively.


We can make use of BinaryReader and BinaryWriter class for reading and writing binary files respectively.

While creating object of BinaryReader and BinaryWriter we have to pass stream object as constructor argument. First we create the object of FileStream class which references to the specified file. And the object of FileStream class ,we pass as constructor argument of BinaryReader and BinaryWriter class.

For  writing in Binary File, the code snippet :-

FileStream fs = new FileStream("c:\\test.bin",FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(true);  //writing bool value
bw.Write(Convert.ToByte('a')); //writing byte
bw.Write('a');                 //writing character
bw.Write("string");            //string
bw.Write(123);                 //number
bw.Write(123.12);              // double value
bw.Close();

For reading Binary File, the code snippet:-

FileStream fs1 = new FileStream("c:\\test.bin", FileMode.Open);
BinaryReader br = new BinaryReader(fs1);
bool b =  br.ReadBoolean();
byte _byte = br.ReadByte();
char _char = br.ReadChar();
string _string = br.ReadString();
int _int = br.ReadInt16();
double _dbl = br.ReadDouble();
Console.WriteLine(b);
Console.WriteLine(_byte);
Console.WriteLine(_char);
Console.WriteLine(_string);
Console.WriteLine(_int);
Console.WriteLine(_dbl);
fs1.Close();