c# – 内存流不可扩展

前端之家收集整理的这篇文章主要介绍了c# – 内存流不可扩展前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试阅读一个电子邮件附件,我正在获得一个“内存流不可扩展”的错误.我研究了这一些,大多数解决方案似乎与确定缓冲区大小有关,但我已经在做.我对内存流不是很有经验,所以我想知道为什么这是一个问题.谢谢.
  1. foreach (MailMessage m in messages)
  2. {
  3. byte[] myBuffer = null;
  4. if (m.Attachments.Count > 0)
  5. {
  6. //myBuffer = new byte[25 * 1024]; old way
  7. myBuffer = new byte[m.Attachments[0].ContentStream.Length];
  8. int read;
  9. while ((read = m.Attachments[0].ContentStream.Read(myBuffer,myBuffer.Length)) > 0)
  10. {
  11. // error occurs on executing next statement
  12. m.Attachments[0].ContentStream.Write(myBuffer,read);
  13. }
  14.  
  15. ... more unrelated code ...

解决方法

如果您通过预先分配的字节数组创建了一个MemoryStream,则它不能展开(即,比您在启动时指定的大小更长).相反,为什么不使用:
  1. using (var ms = new MemoryStream())
  2. {
  3. // Do your thing,for example:
  4. m.Attachments[0].ContentStream.CopyTo(ms);
  5.  
  6. return ms.ToArray(); // This gives you the byte array you want.
  7. }

猜你在找的C#相关文章