Problem reading stream

Suppose we have a block of code like this:

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

The read method can read anywhere from 1 to 1000 bytes, leaving the stream balance unread.

This is what the book says in C #.

I don’t understand why ReadI read the method somewhere from the stream? Does he not read the entire stream?

And he says the workaround 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);

The code above is also provided by the book as a workaround. I am trying to figure out if the read method starts to read to the end and writes all the bytes in the specified range to the byte array. Why does he use bytesReadas a starting point ins.Read(data,bytesRead,dataLength-bytesRead);

Thanks in advance.

+5
source share
5 answers

, , Read... -. , NetworkStream , . FileStream. , , , , . , , , , " , ", Read , .

, . , , , , . , bytesRead .

+8

" 1 1000 " " 1 , 2 , 1000 ". , . .

+4

1000 Read.

- , , , , , , .

, , 1000 . , , , , , , 1000 . , ( , ), .

+2

, Read - ? ?

. . itowlson .

, .

, , . Read .

bytesRead s.Read(data, bytesRead, dataLength-bytesRead);

bytesRead " ". , .

+1

Read, , , , , read . , 500 , -, , , 1000 , 1000 , , , . , 500 , , . 1000 - , 1000 .

0
source

All Articles