以下是我正在使用的代码。基本上它只是循环遍历数组,将文件添加到zip,然后将zip保存到内存流,然后通过电子邮件发送附件。
当我在调试中查看该项时,我可以看到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的附件,那么附加此项目的正确方法是什么?
答案 0 :(得分:2)
我怀疑对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
}