【问题标题】:C# Zip Saving byte[] into zip, converting to stream, sending mail as a mail attachment - proper way to attachment documentC# Zip 将字节 [] 保存为 zip,转换为流,将邮件作为邮件附件发送 - 附件文档的正确方法
【发布时间】:2014-06-24 18:26:53
【问题描述】:

所以下面是我正在使用的代码。基本上它只是遍历一个数组,将文件添加到 zip 中,然后将 zip 保存到内存流中,然后通过电子邮件发送附件。

当我在调试中查看项目时,我可以看到 zip 文件有大约 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 的调用很可能会关闭附件流,从而导致您丢失数据。你用的是什么 Zip 库?
  • 这里最重要的软件(zip.)没有被识别出来。
  • 除了 Jim 的回答(尽管您现在可能已经把这个问题抛在脑后;这对其他读者来说更重要),您可以简单地重置 Stream 的位置。像这样:stackoverflow.com/a/2267750/722393.

标签: c# zip byte memorystream


【解决方案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
}

【讨论】:

  • Jim 我可以看到 Attachment data = new Attachment(attachmentstream, "documentrequest.zip");附件流的大小仍然正确,但附件的大小为 -1
  • 吉姆 - 你的建议实际上关闭了流,然后邮件无法发送
  • 忽略我上面关于关闭流的评论,但仍然是无效文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 2019-01-16
  • 2013-07-11
  • 1970-01-01
相关资源
最近更新 更多