Tuesday 25 October 2011

Reading binary data in C#

A few weeks ago I was trying to read binary data (e.g. a file) for a client application (to test a server application) and I struggled, there was no easy way of reading a file into a byte array, that I could think of.

A little bit of googling and I found this, which works pretty well, but it turns out that there is an inbuilt method into the framework: BinaryReader, which has the advantage of using exactly two lines of code, relevant code below:

   1 BinaryReader br = new BinaryReader(File.Open(@"c:\searchterms.txt",FileMode.Open));
   2 
   3 byte[] dgram = br.ReadBytes((int)br.BaseStream.Length);


I can now send the dgram array to my server application :)

No comments:

Post a Comment