Creating Zip Files from Memory Stream C#

前端 未结 5 2132
执笔经年
执笔经年 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;

提交回复
热议问题