Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 内存流不可扩展_C#_Email_Stream - Fatal编程技术网

C# 内存流不可扩展

C# 内存流不可扩展,c#,email,stream,C#,Email,Stream,我正在尝试读取电子邮件附件,但收到“内存流不可扩展”错误。我对此进行了研究,其中一些和大多数解决方案似乎与动态确定缓冲区大小有关,但我已经在这样做了。我对内存流不是很有经验,所以我想知道为什么这是一个问题。谢谢 foreach (MailMessage m in messages) { byte[] myBuffer = null; if (m.Attachments.Count > 0) { //myBuffer = new byte[25 * 1024];

我正在尝试读取电子邮件附件,但收到“内存流不可扩展”错误。我对此进行了研究,其中一些和大多数解决方案似乎与动态确定缓冲区大小有关,但我已经在这样做了。我对内存流不是很有经验,所以我想知道为什么这是一个问题。谢谢

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);
使用一行写入先前创建的
内存流
,例如

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

如果流的目的是读取附件,为什么突出显示的行会写入附件?此代码段是一个较大进程的一部分,该进程将附件读入缓冲区,然后将缓冲区(以及电子邮件正文中的xmlDocument)传递给另一个进程。我突出显示了生成异常的行。为了澄清,关键是要使用空的(无参数)
MemoryStream()
ctor,它将它创建为可扩展的。