来自MemoryStream的电子邮件附件是空的 [英] email attachment from the MemoryStream comes empty
本文介绍了来自MemoryStream的电子邮件附件是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
_data是附件数据的byte []数组。
_data is a byte[] array of Attachment data.
当我这样做:
var ms = new MemoryStream(_data.Length);
ms.Write(_data,0,_data.Length);
mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));
附件为空。实际上outlook显示文件大小,但它是不正确的。
Attachment comes empty. Actually outlook shows the filesize but it's incorrect.
嗯,我以为在_data有一个问题。然后我决定尝试这种方法:
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?
推荐答案
使用第一个表单,您不会倒带流:
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.
创建MemoryStream的一种更简单的方法是仅使用构造函数:
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));
这篇关于来自MemoryStream的电子邮件附件是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文