内存流不可扩展

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

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,则无法扩展(即,比您启动时指定的大小更长)。 相反,为什么不使用:

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

你需要更换线路

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