我正在尝试压缩 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 服务应用程序的一部分,所以我不想在磁盘上创建文件,并且电子邮件还包含 xslt 转换的 xml 树的备用视图,所以我不想要完全不同解决方案。
任何建议为什么 zip 文件已损坏?