Creating Zip Files from Memory Stream C#

前端 未结 5 2129
执笔经年
执笔经年 2021-02-04 06:51

Basically the user should be able to click on one link and download multiple pdf files. But the Catch is I cannot create files on server or anywhere. Everything has to be in mem

相关标签:
5条回答
  • 2021-02-04 07:27

    This code Will help You in Creating Zip by multiple pdf files which you will get Each file from a Download Link.

            using (var outStream = new MemoryStream())
                    {
                        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
                        {
                            for (String Url in UrlList)
                            {
                                WebRequest req = WebRequest.Create(Url);
                                req.Method = "GET";
                                var fileInArchive = archive.CreateEntry("FileName"+i+ ".pdf", CompressionLevel.Optimal);
                                using (var entryStream = fileInArchive.Open())
                                using (WebResponse response = req.GetResponse())
                                {
                                    using (var fileToCompressStream = response.GetResponseStream())
                                    {
                                        entryStream.Flush();
                                        fileToCompressStream.CopyTo(entryStream);
                                        fileToCompressStream.Flush();
                                    }
                                }
                               i++;
                            }
    
                        }
                        using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create))
                        {
                            outStream.Seek(0, SeekOrigin.Begin);
                            outStream.CopyTo(fileStream);
                        }
                    }
    

    Namespace Needed: System.IO.Compression; System.IO.Compression.ZipArchive;

    0 讨论(0)
  • 2021-02-04 07:32

    You could generate your pdf files and store it in IsolatedStorageFileStream then you could zip content from that storage.

    0 讨论(0)
  • 2021-02-04 07:35

    Below code is to get files from a directory in azure blob storage, merge in a zip and save it in azure blob storage again.

        var outputStream = new MemoryStream();
        var archive = new ZipArchive(outputStream, ZipArchiveMode.Create, true);
    
        CloudBlobDirectory blobDirectory = appDataContainer.GetDirectoryReference(directory);
        
        var blobs = blobDirectory.ListBlobs();
    
        foreach (CloudBlockBlob blob in blobs)
        {
            var fileArchive = archive.CreateEntry(Path.GetFileName(blob.Name),CompressionLevel.Optimal);
    
            MemoryStream blobStream = new MemoryStream();
            if (blob.Exists())
            {
                blob.DownloadToStream(blobStream);
                blobStream.Position = 0;
            }
    
            var open = fileArchive.Open();
            blobStream.CopyTo(open);
            blobStream.Flush();
            open.Flush();
            open.Close();
    
            if (deleteBlobAfterUse)
            {
                blob.DeleteIfExists();
            }
        }
        archive.Dispose();
    
        CloudBlockBlob zipBlob = appDataContainer.GetBlockBlobReference(zipFile);
    
        zipBlob.UploadFromStream(outputStream);
    

    Need the namespaces:

    • System.IO.Compression;
    • System.IO.Compression.ZipArchive;
    • Microsoft.Azure.Storage;
    • Microsoft.Azure.Storage.Blob;
    0 讨论(0)
  • 2021-02-04 07:37

    Below is the code which is creating a zip file in MemoryStream using ZipOutputStream class which is exists inside ICSharpCode.SharpZipLib dll.

    FileStream fileStream = File.OpenRead(@"G:\1.pdf");
    MemoryStream MS = new MemoryStream();
    
    byte[] buffer = new byte[fileStream.Length];
    int byteRead = 0;
    
    ZipOutputStream zipOutputStream = new ZipOutputStream(MS);
    zipOutputStream.SetLevel(9); //Set the compression level(0-9)
    ZipEntry entry = new ZipEntry(@"1.pdf");//Create a file that is needs to be compressed
    zipOutputStream.PutNextEntry(entry);//put the entry in zip
    
    //Writes the data into file in memory stream for compression 
    while ((byteRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        zipOutputStream.Write(buffer, 0, byteRead);
    
    zipOutputStream.IsStreamOwner = false;
    fileStream.Close();
    zipOutputStream.Close();
    MS.Position = 0;
    
    0 讨论(0)
  • 2021-02-04 07:45

    This link describes how to create a zip from a MemoryStream using SharpZipLib: https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#wiki-anchorMemory. Using this and iTextSharp, I was able to zip multiple PDF files that were created in memory.

    Here is my code:

    MemoryStream outputMemStream = new MemoryStream();
    ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
    
    zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
    byte[] bytes = null;
    
    // loops through the PDFs I need to create
    foreach (var record in records)
    {
        var newEntry = new ZipEntry("test" + i + ".pdf");
        newEntry.DateTime = DateTime.Now;
    
        zipStream.PutNextEntry(newEntry);
    
        bytes = CreatePDF(++i);
    
        MemoryStream inStream = new MemoryStream(bytes);
        StreamUtils.Copy(inStream, zipStream, new byte[4096]);
        inStream.Close();
        zipStream.CloseEntry();
    }
    
    zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
    zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.
    
    outputMemStream.Position = 0;
    
    return File(outputMemStream.ToArray(), "application/octet-stream", "reports.zip");
    

    The CreatePDF Method:

    private static byte[] CreatePDF(int i)
    {
        byte[] bytes = null;
        using (MemoryStream ms = new MemoryStream())
        {
            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new Paragraph("Hello World " + i));
            document.Close();
            writer.Close();
            bytes = ms.ToArray();
        }
    
        return bytes;
    }
    
    0 讨论(0)
提交回复
热议问题