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

时间:2016-04-04 17:00:23

标签: c# tcp netstream 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?

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

I work in this manner:

using (NetworkStream netStream = new NetworkStream(...))
using (BinaryReader br = new BinaryReader(netStream))
{
    byte x;
    do
    {
        try
        {
            x = br.ReadByte();
        }
        catch (EndOfStreamException exception)
        {
            x = Byte.MinValue;
        }
    } while (x != byte.MinValue);
}