内存流不可扩展

时间:2013-12-06 11:31:57

标签: c# email stream

我正在尝试阅读电子邮件附件,而我收到的“内存流无法展开”错误。我研究了一些,大多数解决方案似乎与动态确定缓冲区的大小有关,但我已经这样做了。我对内存流不是很熟悉,所以我想知道为什么这是一个问题。感谢。

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 ...

2 个答案:

答案 0 :(得分:29)

如果在预先分配的字节数组上创建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.
}

答案 1 :(得分:4)

您需要替换

m.Attachments[0].ContentStream.Write(myBuffer, 0, read);
带有写入先前创建的MemoryStream的行的

,例如

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);
      }