加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 内存流不可扩展

发布时间:2020-12-15 06:46:48 所属栏目:百科 来源:网络整理
导读:我正在尝试阅读一个电子邮件附件,我正在获得一个“内存流不可扩展”的错误.我研究了这一些,大多数解决方案似乎与确定缓冲区大小有关,但我已经在做.我对内存流不是很有经验,所以我想知道为什么这是一个问题.谢谢. foreach (MailMessage m in messages){ byte[
我正在尝试阅读一个电子邮件附件,我正在获得一个“内存流不可扩展”的错误.我研究了这一些,大多数解决方案似乎与确定缓冲区大小有关,但我已经在做.我对内存流不是很有经验,所以我想知道为什么这是一个问题.谢谢.
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,myBuffer.Length)) > 0)
      {
          // error occurs on executing next statement
          m.Attachments[0].ContentStream.Write(myBuffer,read);
      }

      ... more unrelated code ...

解决方法

如果您通过预先分配的字节数组创建了一个MemoryStream,则它不能展开(即,比您在启动时指定的大小更长).相反,为什么不使用:
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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读