MemoryStream 中的电子邮件附件为空
_data 是附件数据的 byte[] 数组。
当我这样做时:
var ms = new MemoryStream(_data.Length);
ms.Write(_data,0,_data.Length);
mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));
附件为空。实际上 Outlook 显示了文件大小,但它不正确。
好吧,我以为我的_data 有问题。然后我决定尝试这种方法:
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));
这很有效。第一个有什么问题吗?
_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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用第一种形式,您不会“倒带”流:
因此它尝试从流的末尾读取,那里没有任何数据。
创建 MemoryStream 的一种更简单的方法是仅使用构造函数:
With the first form, you're not "rewinding" the stream:
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:
不要使用 GetBuffer。使用 ms.ToArray()。
Do not use GetBuffer. Use
ms.ToArray().