Monday, July 28, 2008

C# : Reading a binary file

I needed to read a file into a buffer for subsequent encoding.

Made the mistake of usuing TextReader which of course has issues becaise the EOF could be anywhere for a bionary file. Also you don't know how big the file is and you don't want to use Peek and read one character at a time.

Came up with the following:


// Note: This is a binary file so can't use EOF

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte[] bArray = new byte[br.BaseStream.Length];
bArray = br.ReadBytes(Convert.ToInt32(br.BaseStream.Length));
return bArray;

catch (Exception ex)


No comments: