2

我正在使用 GZIPStream 和 MemoryStream 压缩一个 CSV 文件,并注意到结果文件有些奇怪。似乎 CSV 没有被正确识别。这显示文件何时附加到电子邮件,但在保存在 Windows 桌面上时工作正常。

这是处理 gzip 部分的当前代码段:

GZipStream gStream = null;
        MemoryStream mStream = null;
        MemoryStream mStream2 = null;
        try
        {
            if (attachment.Length > 0)
            {                    
                mStream = new MemoryStream();

                gStream = new GZipStream(mStream, CompressionMode.Compress);                    
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(attachment.ToString());
                gStream.Write(bytes, 0, bytes.Length);
                gStream.Close();

                mStream2 = new MemoryStream(mStream.ToArray());
                Attachment emailAttachement = new Attachment(mStream2, "myGzip.csv.gz", "application/x-Gzip");                                         
                mailMessage.Attachments.Add(emailAttachement);
            }

        }
4

3 回答 3

2

我能够使用下面的代码进行 gzip 压缩并发送 csv。在调用其 Close() 方法之前,GZipStream 不会完成写入。当创建 gzipStream 的 using 块完成时会发生这种情况。即使在 using 块完成后也会关闭流输出,但仍可以使用 ToArray() 或 GetBuffer() 方法从输出流中检索数据。请参阅此博客条目以获取更多信息。

public void SendEmailWithGZippedAttachment(string fromAddress, string toAddress, string subject, string body, string attachmentText)
{
        const string filename = "myfile.csv.gz";
        var message = new MailMessage(fromAddress, toAddress, subject, body);

        //Compress and save buffer
        var output = new MemoryStream();
        using (var gzipStream = new GZipStream(output, CompressionMode.Compress))
        {
            using(var input = new MemoryStream(Encoding.UTF8.GetBytes(attachmentText)))
            {
                input.CopyTo(gzipStream);
            }
        }
        //output.ToArray is still accessible even though output is closed
        byte[] buffer = output.ToArray(); 

        //Attach and send email
        using(var stream = new MemoryStream(buffer))
        {
            message.Attachments.Add(new Attachment(stream, filename, "application/x-gzip"));
            var smtp = new SmtpClient("mail.myemailserver.com") {Credentials = new NetworkCredential("username", "password")};
            smtp.Send(message);
        }
}
于 2011-02-15T03:48:57.513 回答
2

所有建议的答案都不起作用。在这里找到了答案:

限制之一是您不能为放置在存档中的文件命名。

http://msdn.microsoft.com/en-us/magazine/cc163727.aspx

于 2011-02-16T14:03:01.477 回答
0

GZipStream 不会创建 zip 存档;它只是实现了压缩算法。

请参阅此 MSDN 示例以创建 zip 文件:http: //msdn.microsoft.com/en-us/library/ywf6dxhx.aspx

于 2011-02-15T00:50:17.157 回答