Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core create on memory zipfile

I am working on an MVC project where I create dynamically pdf files(wkhtmltopdf) which I want to return in a zip file. The pdf files are generated on fly - I don't need to store them, so my code to return a single file is:

File(pdfBytes, "application/pdf", "file_name")

Taking a look on Microsoft docs their example goes through stored files:

 string startPath = @"c:\example\start";
 string zipPath = @"c:\example\result.zip";
 string extractPath = @"c:\example\extract";

 ZipFile.CreateFromDirectory(startPath, zipPath);
 ZipFile.ExtractToDirectory(zipPath, extractPath);

In my case I want to create N pdf files and return it to the view as a zip.. Something like:

ZipFile zip = new ZipFile();
foreach(var html in foundRawHTML)
{
//create pdf

//append pdf to zip
}

return zip;

Although this is not doable because:

  1. ZipFile and File are statics and cannot be instatiated
  2. There is no way to add a file into a zip on fly(in memory)

Any help is welcome

like image 879
George George Avatar asked Nov 19 '18 16:11

George George


People also ask

Is ZIP compressed?

Zipped (compressed) files take up less storage space and can be transferred to other computers more quickly than uncompressed files. In Windows, you work with zipped files and folders in the same way that you work with uncompressed files and folders.

What is ZIP archive in C#?

Add Files or Folders to ZIP Archives Programmatically in C# April 22, 2020 · 5 min · Usman Aziz. The ZIP archives are used to compress and keep one or more files or folders into a single container. A ZIP archive encapsulates the files and folders as well as holds their metadata information.


1 Answers

You can use in memory byte arrays and ZipArchive from System.IO.Compression, there is no need to map the local drive:

    public static byte[] GetZipArchive(List<InMemoryFile> files)
        {
            byte[] archiveFile;
            using (var archiveStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        var zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
                        using (var zipStream = zipArchiveEntry.Open())
                            zipStream.Write(file.Content, 0, file.Content.Length);
                    }
                }

                archiveFile = archiveStream.ToArray();
            }

            return archiveFile;
        }

public class InMemoryFile
    {
        public string FileName { get; set; }
        public byte[] Content { get; set; }
    }
like image 134
Andrei Filimon Avatar answered Sep 20 '22 07:09

Andrei Filimon