To access the contents of a MemoryStream file after it is closed , use the ToArray() or GetBuffer() methods. The following code demonstrates how to get the contents of a memory buffer as a UTF8 encoded string.
byte[] buff = stream.ToArray(); return Encoding.UTF8.GetString(buff,0,buff.Length);
Note. ToArray() easier to use than GetBuffer() , because ToArray() returns the exact length of the stream, not the size of the buffer (which may be larger than the contents of the stream). ToArray() makes a copy of the bytes.
Note: GetBuffer() more advanced than ToArray() since it does not make a copy of bytes. You need to take care of the possible undefined bytes at the end of the buffer by counting the length of the stream, not the size of the buffer. Using GetBuffer() highly recommended if the stream size is more than 80,000 bytes, because a copy of ToArray will be allocated in a bunch of large objects, where its life time can become problematic.
It is also possible to clone the original MemoryStream as follows in order to facilitate access to it via StreamReader, for example.
using (MemoryStream readStream = new MemoryStream(stream.ToArray())) { ... }
The ideal solution is to access the original MemoryStream until it is closed, if possible.
Simon Giles Jun 17 '15 at 15:21 2015-06-17 15:21
source share