0
votes

I've got a BinaryReader reading in a number of bytes into an array. The underlying Stream for the reader is a BufferedStream(whose underlying stream is a network stream). I noticed that sometimes the reader.Read(arr, 0, len) method is returning different(wrong) results than reader.ReadBytes(len).

Basically my setup code looks like this:

var httpClient = new HttpClient();
var reader = new BinaryReader(new BufferedStream(await httpClient.GetStreamAsync(url).ConfigureAwait(false)));

Later on down the line, I'm reading a byte array from the reader. I can confirm the sz variable is the same for both scenarios.

int sz = ReadSize(reader); //sz of the array to read
if (bytes == null || bytes.Length <= sz)
{
    bytes = new byte[sz];
}

//reader.Read will return different results than reader.ReadBytes sometimes
//everything else is the same up until this point
//var tempBytes = reader.ReadBytes(sz); <- this will return right results
reader.Read(bytes, 0, sz); // <- this will not return the right results sometimes

It seems like the reader.Read method is reading further into the stream than it needs to or something, because the rest of the parsing will break after this happens. Obviously I could stick with reader.ReadBytes, but I want to reuse the byte array to go easy on the GC here.

Would there ever be any reason that this would happen? Is a setting wrong or something?

1
Might be something related to the fact that it's a network stream? When you create the new byte array you "freeze" a little part of the stream, but when you later parse that "freezed" stream with the rest of it it won't match. Caution: never worked with network stream, totally flying by my pants :) - Davide Vitali
Under which condition ReadBytes can read less bytes then requested? Under which condition Read can read less bytes then requested? How this conditions different? - user4003407

1 Answers

0
votes

Make sure you clear out bytes array before calling this function because Read(bytes, 0, len) does NOT clear given byte array, so some previous bytes may conflict with new one. I also had this problem long ago in one of my parsers. just set all elements to zero, or make sure that you are only reading (parsing) up to given len