I believe that there is actually hidden option 4:
- Read the data as it becomes available, looping in the same way as usual by hand. It will return a value less than the number of bytes you requested if it reaches the end of the stream while reading.
This is slightly different from your option 2, as it merges the stream as the data becomes available - it does not wait until it can read all the data in one go.
It is easy to show that it returns fewer bytes than you requested if it reaches the end:
var ms = new MemoryStream(new byte[10]); var readData = new BinaryReader(ms).ReadBytes(100); Console.WriteLine(readData.Length);
It is harder to prove part of the loop, without a user thread that explicitly requires several Read calls to return all the data.
The documentation is not as clear as it can be, but part of the return value is at least somewhat useful:
A byte array containing data read from the underlying stream. This may be less than the number of bytes requested if the end of the stream is reached .
Pay attention to the final part that I have selected and compare it with Stream.Read :
The total number of bytes read in the buffer. This can be less than the number of bytes requested if the number of bytes is currently not available , or zero (0) if the end of the stream is reached.
If you expect an exact amount of data, and only this amount will be useful, I suggest you write a ReadExactly method that throws Read and throws EndOfStreamException if you need more data than the stream provided before it was closed.
Jon skeet
source share