email attachment from the MemoryStream comes empty

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

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

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

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

回答1:

With the first form, you're not "rewinding" the stream:

ms.Position = 0; 

So it was trying to read from the end of the stream, where there wasn't any data.

A simpler way of creating the MemoryStream is to just use the constructor though:

var ms = new MemoryStream(_data); mailMessage.Attachments.Add(new Attachment(ms, attachment.Name)); 


回答2:

Do not use GetBuffer. Use ms.ToArray().



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!