Skip to content

Instantly share code, notes, and snippets.

@n1ckfg
Created September 20, 2017 13:36
Show Gist options
  • Save n1ckfg/08b53d14242443bac30ae557d709adc2 to your computer and use it in GitHub Desktop.
Save n1ckfg/08b53d14242443bac30ae557d709adc2 to your computer and use it in GitHub Desktop.
Compress and decompress using SharpZipLib in Unity
// http://www.sebaslab.com/how-to-compress-and-decompress-binary-stream-in-unity/
using ICSharpCode.SharpZipLib.BZip2;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
static void Compress (string nameOfTheFileToSave, ISerializable objectToSerialize)
{
using (FileStream fs = new FileStream(nameOfTheFileToSave, FileMode.Create))
{
using (MemoryStream objectSerialization = new MemoryStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(objectSerialization, objectToSerialize);
using (BinaryWriter binaryWriter = new BinaryWriter(fs))
{
binaryWriter.Write(objectSerialization.GetBuffer().Length); //write the length first
using (BZip2OutputStream osBZip2 = new BZip2OutputStream(fs))
{
osBZip2.Write(objectSerialization.GetBuffer(), 0, objectSerialization.GetBuffer().Length); //write the compressed file
}
}
}
}
}
static void Decompress(string nameOfTheFileToLoad)
{
using (FileStream fs = new FileStream(nameOfTheFileToLoad, FileMode.Open))
{
using (BinaryReader binaryReader = new BinaryReader(fs))
{
int length = binaryReader.ReadInt32(); //read the length first
byte[] bytesUncompressed = new byte[length]; //you can convert this back to the object using a MemoryStream ;)
using (BZip2InputStream osBZip2 = new BZip2InputStream(fs))
{
osBZip2.Read(bytesUncompressed, 0, length); //read the decompressed file
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment