Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Zip File from List<Byte[]> in Memory

I have a web services that returns a list of files. Something like this:

public FileModel(){
  string FileName {get;set;}
  byte[] FileStream {get;set;}
  string FileType {get;set;} 
}

My Service would return:

  List<FileModel> files;

I have to return this list to browser, so I need to compress these files into a zip folder.

However, I cant figure out how to do this, as .NET ZipArchive CreateFromDirectory is requiring me to provide a directory where the file to be zipped are. But I don't have a directory, I just have this list. How can I covert this list to a zipped folder.

like image 609
Mark Avatar asked Aug 22 '26 16:08

Mark


1 Answers

Given

public FileModel(){
    string FileName {get;set;}
    byte[] FileStream {get;set;}
    string FileType {get;set;} 
}

The following was written to create a zip file

static class FileModelCompression {

    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);
                }
            }// disposal of archive will force data to be written to memory stream.
            ms.Position = 0; //reset memory stream position.
            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;
    }
}
like image 109
Nkosi Avatar answered Aug 25 '26 06:08

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!