Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

precautions for reading from a memorystream in c#

I recently came across this web page http://www.yoda.arachsys.com/csharp/readbinary.html explaining what precautions to take when reading from a filestream. The gist of it is that the following code doesnt 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 as the third argument for Read is a maximum of bytes to be read, and you should use Read's return value to check how much actually got read.

My question is should you take the same precautions when reading from a memorystream and under which circumstances might Read return before all bytes are read?

like image 975
Bas Smit Avatar asked Mar 01 '23 07:03

Bas Smit


2 Answers

Well, I believe the current implementation of MemoryStream will always fill the buffer if it can - unless you've got some evil class derived from it. It's not guaranteed though, as far as I can see. The documentation even contains the warning:

An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

Personally, I'd always code this defensively unless it makes things much easier. You never know when someone will change the type of stream and not notice what's happened.

Normally with a MemoryStream though, I want all the bytes at once: so I call MemoryStream.ToArray. This is guaranteed to work, and if someone changes the code to not use a MemoryStream, it will fail to compile as that member's only on MemoryStream. For general streams, I use a utility method which reads fully from a stream and returns a byte array.

like image 185
Jon Skeet Avatar answered Mar 08 '23 07:03

Jon Skeet


I cant think of any reason for a normal MemoryStream. Unmanaged might be a different story.

Anyways, the GetBuffer() ToArray() command is always handy. :)

like image 22
leppie Avatar answered Mar 08 '23 07:03

leppie