Skip to content

Instantly share code, notes, and snippets.

@cameronpresley
Created November 26, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronpresley/1c2f765f6fcc9c17714a58c37b7d22d1 to your computer and use it in GitHub Desktop.
Save cameronpresley/1c2f765f6fcc9c17714a58c37b7d22d1 to your computer and use it in GitHub Desktop.
Zip/Unzip a compressed folder in memory
using System;
using System.IO.Compression;
using System.Text;
public class InMemoryZipCompresser
{
public byte[] Compress (string fileContents)
{
using (var ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen:true))
{
var jsonFile = archive.CreateEntry("contents.json");
using (var entryStream = jsonFile.Open())
{
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write(Encoding.UTF8.GetString(Encoding.Default.GetBytes(fileContents)));
}
}
}
return ms.ToArray();
}
}
public string Decompress(byte[] zipped)
{
using (var zippedStream = new MemoryStream(zipped))
{
using (var archive = new ZipArchive(zippedStream))
{
var file = archive.GetEntry("contents.json");
if (file == null) return null;
using (var unzippedEntryStream = file.Open())
{
using (var ms = new MemoryStream())
{
unzippedEntryStream.CopyTo(ms);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment