email attachment from the MemoryStream comes empty

iLe*_*ing 13 c# email system.net.mail email-attachments

_data is a byte[] array of Attachment data.

When I'm doing this:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));
Run Code Online (Sandbox Code Playgroud)

Attachment comes empty. Actually outlook shows the filesize but it's incorrect.

Well, I thought there is a problem in my _data. Then I decided to try this approach:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 fs = new FileStream(@"c:\Temp\"+attachment.Name,FileMode.CreateNew);
 fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
 fs.Flush();
 fs.Close();
 mailMessage.Attachments.Add(new Attachment(@"c:\Temp\" + attachment.Name));
Run Code Online (Sandbox Code Playgroud)

And that works. What's wrong with the first one?

Jon*_*eet 35

使用第一个表单,您不会"重绕"流:

ms.Position = 0;
Run Code Online (Sandbox Code Playgroud)

所以它试图从流的末尾读取,那里没有任何数据.

创建MemoryStream的一种更简单的方法是使用构造函数:

var ms = new MemoryStream(_data);
mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));
Run Code Online (Sandbox Code Playgroud)

  • 哦..等等......其实就是这样......我确定我之前尝试过,但它没有用.可能我搞砸了别的东西...... (2认同)