Create normal zip file programmatically

后端 未结 11 869
野的像风
野的像风 2020-12-05 00:06

I have seen many tutorials on how to compress a single file in c#. But I need to be able to create a normal *.zip file out of more than just one file. Is there anything in .

11条回答
  •  Happy的楠姐
    2020-12-05 00:30

    You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5

    You have to add System.IO.Compression as a reference.

    Example: Generating a zip of PDF files

    using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
    {
        using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
        {
            foreach (var creditNumber in creditNumbers)
            {
                var pdfBytes = GeneratePdf(creditNumber);
                var fileName = "credit_" + creditNumber + ".pdf";
                var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
                using (var zipStream = zipArchiveEntry.Open())
                    zipStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
            }
        }
    }
    

提交回复
热议问题