C#从流中压缩和压缩CSV [英] C# Compress and zip csv from stream

查看:241
本文介绍了C#从流中压缩和压缩CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MemoryStream,它从DataTable中提取数据.目前,这会送入MailMessage附件,并邮寄出附加到该邮件的csv.我需要做的是压缩和压缩它.

I have a MemoryStream which pulls data from a DataTable. Currently this feeds into a MailMessage Attachment and mails out a csv attached to the mail. What I need to do is to compress and zip it.

因此,现在我要遍历DataTable的每一行,添加适当的逗号,并将其流式传输出去.它会生成一个包含数据的.bin文件.通过添加名称作为Attachment参数,它将作为有效的csv文件发送到客户端.

So right now I am iterating through each row of a DataTable, adding appropriate commas, and streaming it out. It results in a .bin file with the data. By adding a name as an Attachment argument it sends to the client as a valid csv file.

mail.Attachments.Add(new Attachment(stream, "report.csv"));

在将csv添加为附件之前,有人可以帮助我压缩和压缩csv吗?最好没有外部库.谢谢.

Can anyone help as to how I could compress and zip the csv before adding it as an attachment? Preferably without external libraries. Thank you.

推荐答案

对于以前的答案,使用类似的模型,

For a previous answer, with a model like this,

public FileModel(){
    public string FileName {get;set;}
    public Stream FileStream {get;set;}
}

定义了以下扩展方法来创建要归档的zip存档.

The following extension methods were defined to create a zip archive to stream.

public static class ZipArchiveExtensions {    
    public static Stream Compress(this IEnumerable<FileModel> files) {
        if (files.Any()) {
            var ms = new MemoryStream();
            using(var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) {
                foreach (var file in files) {
                    var entry = archive.add(file);
                }
            }
            ms.Position = 0;
            return ms;
        }
        return null;
    }

    private static ZipArchiveEntry add(this ZipArchive archive, FileModel file) {
        var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
        using (var stream = entry.Open()) {
            file.FileStream.CopyTo(stream);
        }
        return entry;
    }
}

现在,您可以在添加压缩的csv文件作为附件之前添加一个步骤

With that you can now add a step before adding the compressed csv file(s) as attachments

//...other code

var files = new FileModel[] {
    new FileModel {
        FileName = "report1.csv",
        FileStream = stream
    },
    new FileModel {
        FileName = "report2.xlsx",
        FileStream = stream2
    }
};

var zipStream = files.Compress();
mail.Attachments.Add(new Attachment(zipStream, "reports.zip"));

//...other code

这篇关于C#从流中压缩和压缩CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆