Search code examples
c#tcpnetstreambinaryreader

What is the correct way to read from a NetStream through a BinaryReader?


I understood that if you want to read X bytes from a netstream that doing:

netStream.Read(buffer, 0, X);

is not sufficient in all cases, since the Read might only return part of X, so you need to loop until the amount of read bytes equals X.

Another example however wrapped the NetStream in a BinaryReader br and then proceeded with:

br.Read(buffer, 0, X);

My question is:

Is this valid due to the fact that the NetStream is now wrapped by a BinaryReader, or do we still need to take into account that Read might not return all X bytes and loop, just as with reading from the original netstream?


Solution

  • BinaryReader.Read(byte[], int, int) just forwards the call to the underlying stream. The semantics are the same. For this scenario, however, there is also the helper method BinaryReader.ReadBytes(int) which reads a specific number of bytes, so you don't have to keep track of how many bytes have been read yourself.