MemoryStream 中的电子邮件附件为空

发布于 2024-09-19 10:22:08 字数 646 浏览 1 评论 0原文

_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少钕鈤記 2024-09-26 10:22:08

使用第一种形式,您不会“倒带”流:

ms.Position = 0;

因此它尝试从流的末尾读取,那里没有任何数据。

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

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

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));
最偏执的依靠 2024-09-26 10:22:08

不要使用 GetBuffer。使用 ms.ToArray()。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文