Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory stream is not expandable

Tags:

I'm attempting to read an email attachment and I'm getting a "Memory Stream is not expandable" error. I researched this some and most of the solutions seemed related to determining the size of the buffer dynamically, but I'm already doing that. I'm not very experienced with memory streams, so I'd like to know WHY this is a problem. Thanks.

foreach (MailMessage m in messages) {    byte[] myBuffer = null;    if (m.Attachments.Count > 0)    {       //myBuffer = new byte[25 * 1024];  old way        myBuffer = new byte[m.Attachments[0].ContentStream.Length];       int read;       while ((read = m.Attachments[0].ContentStream.Read(myBuffer, 0, myBuffer.Length)) > 0)       {           // error occurs on executing next statement           m.Attachments[0].ContentStream.Write(myBuffer, 0, read);       }        ... more unrelated code ... 
like image 440
Steve Wash Avatar asked Dec 06 '13 11:12

Steve Wash


People also ask

Do I need to dispose memory stream?

MemoryStream does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing a MemoryStream is roughly the same thing as dropping a reference to a byte[] -- the GC will clean both up the same way.

What is memory stream in C#?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


2 Answers

If you create a MemoryStream over a pre-allocated byte array, it can't expand (ie. get longer than the size you specified when you started). Instead, why not just use:

using (var ms = new MemoryStream()) {    // Do your thing, for example:    m.Attachments[0].ContentStream.CopyTo(ms);     return ms.ToArray(); // This gives you the byte array you want. } 
like image 179
Luaan Avatar answered Oct 03 '22 22:10

Luaan


You need to replace the line

m.Attachments[0].ContentStream.Write(myBuffer, 0, read); 

with a line that writes to a previously created MemoryStream, e.g.

foreach (MailMessage m in messages) {    byte[] myBuffer = null;    if (m.Attachments.Count > 0)    {       //myBuffer = new byte[25 * 1024];  old way        myBuffer = new byte[m.Attachments[0].ContentStream.Length];       int read;       MemoryStream ms = new MemoryStream();       while ((read = m.Attachments[0].ContentStream.Read(myBuffer, 0, myBuffer.Length)) > 0)       {           ms.Write(myBuffer, 0, read);       } 
like image 45
Tobias Ramforth Avatar answered Oct 03 '22 22:10

Tobias Ramforth