Precautions for reading from memystream in C #

Hi guys, I recently came across this web page http://www.yoda.arachsys.com/csharp/readbinary.html explaining what precautions to take when reading from a stream. Its essence is that the following code does not always work:

// Bad code! Do not use!
FileStream fs = File.OpenRead(filename);
byte[] data = new byte[fs.Length];
fs.Read (data, 0, data.Length);

This is dangerous because the third argument to read is the maximum number of bytes to read, and you should use the Read return value to check how much you actually read.

My question is, should you take the same precautions when reading from the storage device and under what circumstances can it read the return before all bytes are read?

Thanks Bas

+3
source share
4 answers

Well, I believe that the current implementation MemoryStreamwill always fill the buffer, if possible, if you do not have some kind of evil class derived from it. As far as I know, this is not guaranteed. The documentation contains a warning:

An implementation may return fewer bytes than requested, even if the end of the stream has not been reached.

Personally, I would always code it defensively if this does not simplify the situation. You never know when someone will change the type of stream and not notice what happened.

MemoryStream, , : MemoryStream.ToArray. , - , MemoryStream, MemoryStream. , .

+5

- MemoryStream. .

GetBuffer() ToArray() .:)

+1

, , Read. , , , .

0

MSDN :

... may be less than the number of bytes if that number of bytes is currently unavailable or zero if the end of the stream is equal before all bytes are read.

and

An implementation may return less than requested, even if the end of the stream has not been reached.

Pay attention to the term "implementation ...".

0
source

Source: https://habr.com/ru/post/1718040/


All Articles