Home > Backend Development > C++ > How to Properly Create a ZIP Archive in Memory Using MemoryStream and System.IO.Compression?

How to Properly Create a ZIP Archive in Memory Using MemoryStream and System.IO.Compression?

Linda Hamilton
Release: 2025-01-07 00:30:39
Original
624 people have browsed it

How to Properly Create a ZIP Archive in Memory Using MemoryStream and System.IO.Compression?

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);
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template