Using MemoryStream to Create a ZIP Archive in Memory with System.IO.Compression
While trying to create a ZIP archive using a MemoryStream, you may encounter an issue where the archive is generated but the desired file is missing. This is because ZipArchive requires final bytes to be written for completion. To resolve this:
using (var memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var demoFile = archive.CreateEntry("foo.txt"); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write("Bar!"); } } using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) { memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } }
Passing "true" as the third parameter to ZipArchive allows you to continue using the stream after calling Dispose, ensuring that all necessary information is written to the archive.
The above is the detailed content of How to Properly Create a ZIP Archive in Memory Using MemoryStream and System.IO.Compression?. For more information, please follow other related articles on the PHP Chinese website!