Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream Read Problem

Tags:

c#

.net

stream

Suppose we have a code block like this :

//Assuming s is a stream:
byte[] data = new byte[1000];
s.Read(data,0,data.Length);

The read Method could read anywhere from 1 to 1000 bytes, leaving the balance of the stream unread.

This is what a C# book says.

I don't understand,why Read method would read anywhere from the stream ? It ain't reading all of the stream ?

And it says the work-around should be like this :

//bytesRead will always end up at 1000, unless the stream is itself smaller in length:
int bytesRead = 0;
int chunkSize = 1;
while(bytesRead < data.Length && chunkSize > 0 )
      bytesRead += chunkSize = s.Read(data,bytesRead,dataLength-bytesRead);

This code above is also provided by the book as a work-around. What I am trying to understand whether Read method is beginning to read to the end and write all of the bytes in specified range to byte array. Why is he using the bytesRead as a start point in s.Read(data,bytesRead,dataLength-bytesRead);

Thanks in advance.

like image 309
Tarik Avatar asked Nov 12 '09 19:11

Tarik


2 Answers

The idea is that the data may not be available at the time you call Read... or ever. For example, on a NetworkStream, the data may be arriving more slowly than you are picking it up. Or you might be close to the end of a FileStream. The Stream may know that there are fewer bytes remaining than you asked for, or it may have no way of knowing when or whether the full whack of requested bytes will arrive. So rather than wait for data that may never arrive, or fail with a "not enough bytes, guess again" error, Read reserves the right to return less than you asked for.

Consequently, when reading a chunk into a byte array, you may not be filling the byte array. But you want the next chunk to be appended where the last one left off, rather than overwriting the beginning of the byte array. Hence passing bytesRead as the starting location for placing the next chunk in the byte array.

like image 139
itowlson Avatar answered Sep 22 '22 02:09

itowlson


The phrase "could read anywhere from 1 to 1000 bytes" means "could read 1 byte, or 2 bytes, up to 1000 bytes". It refers to the length of bytes read, not the location. The read will be located at the stream's current position.

like image 22
Skirwan Avatar answered Sep 21 '22 02:09

Skirwan