利用GZIP流和内存流正确压缩CSV

时间:2011-02-14 22:36:05

标签: c# .net memorystream gzipstream

我正在使用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);
            }

        }

3 个答案:

答案 0 :(得分:2)

我能够使用下面的代码gzip压缩并发送csv。在调用Close()方法之前,GZipStream不会完成写入。当创建gzipStream的using块完成时会发生这种情况。即使完成使用块的流输出也已关闭,仍然可以使用ToArray()或GetBuffer()方法从输出流中检索数据。有关详细信息,请参阅此blog entry

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);
        }
}

答案 1 :(得分:1)

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

  

其中一个限制是您无法为存档中的文件命名。

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

答案 2 :(得分:0)

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

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