Created
November 26, 2018 14:01
-
-
Save cameronpresley/1c2f765f6fcc9c17714a58c37b7d22d1 to your computer and use it in GitHub Desktop.
Zip/Unzip a compressed folder in memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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