本文介绍了内存流不可扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试阅读电子邮件附件,而且我收到内存流不可扩展错误。我研究了这一些,大多数解决方案似乎与确定缓冲区大小有关,但我已经在做。我对内存流不是很有经验,所以我想知道为什么这是一个问题。谢谢。
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 ...
推荐答案
如果您通过预先分配的字节数组创建一个MemoryStream,则无法扩展(即,比您在启动时指定的大小更长)。相反,为什么不使用:
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.
}
这篇关于内存流不可扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!