使用foreach循环从URL压缩多个文件

时间:2019-05-05 17:15:20

标签: c# asp.net pdf zip memorystream

我有一个项目,要求从URL链接压缩多个文件。在我的Db中,我有pdf文件名,可以根据URL链接检查并压缩它们。因此,可以说我将其作为URL来源:www.example.com/folder/{pdf file name}。我想将test1.zip与其他其他zip文件一起压缩。即test1.zip, test2.zip, test3.zip

因此,我设法编写了代码来迭代URL链接。但是问题是我设法压缩了一个文件。但实际上,我想压缩多个文件。

我尝试了所有途径,但没有奏效。任何帮助表示赞赏!

这是一个有效的代码:

  

ASP.NET Core

        [HttpGet("zipFiles")]
        public IActionResult ZipPDFFiles()
        {
           //file names coming from db
            var fileNames = _repo.GetFileNames();

            foreach (var filesName in fileNames)
            {
                var urlLink = "https://example.com/folder/" + $"{filesName.PdfFileName}";

                var net = new System.Net.WebClient();
                var data = net.DownloadData(urlLink);

                var file = $"{filesName.PdfFileName}";

                var contentType = "application/zip";

                string zippedFolderName = "Archive.zip";

                using (MemoryStream ms = new MemoryStream())
                {
                    using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        var zipArchiveEntry = archive.CreateEntry($"{file}", System.IO.Compression.CompressionLevel.Fastest);
                        using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(data, 0, data.Length);
                    }
                    return File(ms.ToArray(), contentType, $"{zippedFolderName}");
                }

            }
            return NotFound();
        }

0 个答案:

没有答案