C# - BinaryReader And BinaryWriter Class

BinaryReader And BinaryWriter Class

If you are dealing with binary files, you can use the BinaryReader and BinaryWriter classes. The following example reads binary data from one file and writes it into another, essentially making a copy of the file:

string filePath = @"C:\temp\VS2013Pro.png";
string filePathCopy = @"C:\temp\VS2013Pro_copy.png";
//---open files for reading and writing---
FileStream fs1 = File.OpenRead(filePath);
FileStream fs2 = File.OpenWrite(filePathCopy);
BinaryReader br = new BinaryReader(fs1);
BinaryWriter bw = new BinaryWriter(fs2);
//---read and write individual bytes---
for (int i = 0; i <= br.BaseStream.Length - 1; i++)
    bw.Write(br.ReadByte());
//---close the reader and writer---
br.Close();
bw.Close();

This program first uses the File class to open two files — one for reading and one for writing. The BinaryReader class is then used to read the binary data from the FileStream, and the BinaryWriter is used to write the binary data to the file.

The BinaryReader class contains many different read methods for reading different types of data — Read(), Read7BitEncodedInt(), ReadBoolean(), ReadByte(), ReadBytes(), ReadChar(), ReadChars(), ReadDecimal(), ReadDouble(), ReadInt16(), ReadInt32(), ReadInt64(), ReadSByte(), ReadSingle(), ReadString(), ReadUInt16(), ReadUInt32(), and ReadUInt64().