メモリストリームは拡張できません 質問する

メモリストリームは拡張できません 質問する

メールの添付ファイルを読み込もうとすると、「メモリ ストリームは拡張できません」というエラーが表示されます。この件について少し調べてみたところ、解決策のほとんどはバッファのサイズを動的に決定することに関係しているようでしたが、私はすでにそれを実行しています。メモリ ストリームについてはあまり詳しくないので、なぜこれが問題なのかを知りたいです。よろしくお願いします。

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

ベストアンサー1

事前に割り当てられたバイト配列上に 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.
}

おすすめ記事