0

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?

2
  • 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 :) Commented Jun 26, 2017 at 19:58
  • Under which condition ReadBytes can read less bytes then requested? Under which condition Read can read less bytes then requested? How this conditions different? Commented Jun 26, 2017 at 20:11

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.