gpt4 book ai didi

.net - 压缩电子邮件附件的 MemoryStream

转载 作者:行者123 更新时间:2023-12-02 22:12:58 24 4
gpt4 key购买 nike

我正在尝试压缩 XML 树并将其用作电子邮件附件。带附件的电子邮件发送成功,但创建的 zip 文件始终损坏 - 它不是有效的 zip 文件,但包含二进制数据。

问题重现如下,具体参见BuildAttachment():

static void Main(string[] args)
{
try
{
var report = new XElement("Report",
new XElement("Product",
new XElement("ID", "10000001"),
new XElement("Name", "abcdefghijklm"),
new XElement("Group", "nopqrstuvwxyz")
)
);
var mailMessage = BuildMessage(report);
EmailMessage(mailMessage);
Thread.Sleep(10000);
}
catch (Exception e) { Console.WriteLine(e.Message); }
}
static MailMessage BuildMessage(XElement report)
{
string from = "email1@address.com";
string to = "email2@address.com";
var message = new MailMessage(from, to, "Subject text", "Body text");

var attachment = BuildAttachment(report);
message.Attachments.Add(attachment);

return message;
}
static Attachment BuildAttachment(XElement report)
{
var inStream = new MemoryStream();
report.Save(inStream);
inStream.Position = 0;

var outStream = new MemoryStream();
var compress = new DeflateStream(outStream, CompressionMode.Compress);
inStream.CopyTo(compress);

outStream.Position = 0;
return new Attachment(outStream, "report.zip", "application/zip");
}
static void EmailMessage(MailMessage message)
{
var smtpClient = new SmtpClient("127.0.0.1");
smtpClient.SendCompleted += SendCompletedCallback;
smtpClient.SendAsync(message, null);
}
static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
Console.WriteLine(e.Error.ToString());
}

将问题放在上下文中:它是 Windows 服务应用程序的一部分,所以我不想在磁盘上创建文件,并且电子邮件还包含 xml 树的 xslt 转换的备用 View ,所以我不想一个完全不同的解决方案。

对于 zip 文件损坏的原因有什么建议吗?

最佳答案

我知道这是一个老问题,但当我搜索相同的问题时它出现了。

这是我使用 System.IO.Compression.ZipArchive (requires .NET 4.5 or higher) 添加压缩 (zip) 附件的解决方案[基于acraig5075的回答]:

byte[] report = GetSomeReportAsByteArray();
string fileName = "file.txt";

using (MemoryStream memoryStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Update))
{
ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(fileName);
using (StreamWriter streamWriter = new StreamWriter(zipArchiveEntry.Open()))
{
streamWriter.Write(Encoding.Default.GetString(report));
}
}

MemoryStream attachmentStream = new MemoryStream(memoryStream.ToArray());

Attachment attachment = new Attachment(attachmentStream, fileName + ".zip", MediaTypeNames.Application.Zip);
mail.Attachments.Add(attachment);
}

关于.net - 压缩电子邮件附件的 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11614271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com