I don't know why they're doing that, but it's not a great example in general - for instance, they're using explicit calls to Close
(not in a finally block) on the FileStream
instead of using a using
statement, and also assuming that a single call to Read
will read the whole of a file. Heck, even reading the whole file into a buffer is a bad idea - it would be better to copy a chunk at a time straight into the DeflateStream
.
These things suggest to me that it's not worth worrying about this specific odd bit of code (the extra 100 bytes) within that example. Certainly don't regard it as "best practice".
MSDN examples are usually better than this - although there are plenty of other odd ones.
EDIT: Having reread the code and CodeMelt's answer, it does indeed need the extra 100 bytes - but only because ReadAllBytesFromStream is implemented so badly. Here's a better implementation, which always asks the stream to fill the rest of the buffer:
public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
{
int offset = 0;
int bytesRead;
while ((bytesRead = stream.Read(buffer, offset,
buffer.Length-offset)) > 0)
{
offset += bytesRead;
}
return offset;
}
(Note that there was no need for both offset
and totalCount
as they always had the same value.)