c# – 内存流不可扩展

前端之家收集整理的这篇文章主要介绍了c# – 内存流不可扩展前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试阅读一个电子邮件附件,我正在获得一个“内存流不可扩展”的错误.我研究了这一些,大多数解决方案似乎与确定缓冲区大小有关,但我已经在做.我对内存流不是很有经验,所以我想知道为什么这是一个问题.谢谢.
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 ...
@H_301_5@解决方法
如果您通过预先分配的字节数组创建了一个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.
}
原文链接:https://www.f2er.com/csharp/94668.html

猜你在找的C#相关文章