将byte[]保存为Zip,转换为流,作为邮件附件发送邮件-附件文档的正确方式
本文关键字:文档 方式 byte 保存 Zip 转换 | 更新日期: 2023-09-27 18:10:03
下面是我使用的代码。基本上,它只是循环遍历一个数组,将文件添加到压缩文件中,然后将压缩文件保存到内存流中,然后通过电子邮件发送附件。
当我在调试中查看项目时,我可以看到zipfile有大约20兆字节的数据。当我收到附件时,它只有大约230位的数据,没有内容。任何想法吗?
byteCount = byteCount + docs[holder].FileSize;
if (byteCount > byteLimit)
{
//create a new stream and save the stream to the zip file
System.IO.MemoryStream attachmentstream = new System.IO.MemoryStream();
zip.Save(attachmentstream);
//create the attachment and send that attachment to the mail
Attachment data = new Attachment(attachmentstream, "documentrequest.zip");
theMailMessage.Attachments.Add(data);
//send Mail
SmtpClient theClient = new SmtpClient("mymail");
theClient.UseDefaultCredentials = false;
System.Net.NetworkCredential theCredential = new System.Net.NetworkCredential("bytebte", "2323232");
theClient.Credentials = theCredential;
theClient.Send(theMailMessage);
zip = new ZipFile();
//iterate Document Holder
holder++;
}
else
{
//create the stream and add it to the zip file
//System.IO.MemoryStream stream = new System.IO.MemoryStream(docs[holder].FileData);
zip.AddEntry("DocId_"+docs[holder].DocumentId+"_"+docs[holder].FileName, docs[holder].FileData);
holder++;
}
问题在这里,Attachment data = new Attachment(attachmentstream, "documentrequest.zip");
,一旦我看附件,它的大小是-1,那么什么是正确的方式来附加这个项目?
我怀疑对zip.Save
的调用在写完流之后关闭了流。您可能最终不得不将字节复制到数组中,然后创建一个新的MemoryStream
用于读取。例如:
//create a new stream and save the stream to the zip file
byte[] streamBytes;
using (var ms = new MemoryStream())
{
zip.Save(ms);
// copy the bytes
streamBytes = ms.ToArray();
}
// create a stream for the attachment
using (var attachmentStream = new MemoryStream(streamBytes))
{
//create the attachment and send that attachment to the mail
Attachment data = new Attachment(attachmentstream, "documentrequest.zip");
theMailMessage.Attachments.Add(data);
// rest of your code here
}