C# Compress and zip csv from stream

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 02:29:48

问题


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.

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

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.


回答1:


For a previous answer, with a model like this,

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

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();
            var archive = new ZipArchive(ms, ZipArchiveMode.Create, false);
            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);
            stream.Position = 0;
            stream.Close();
        }
        return entry;
    }
}

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


来源:https://stackoverflow.com/questions/44484786/c-sharp-compress-and-zip-csv-from-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!