Skip to content

Instantly share code, notes, and snippets.

@BrutalSimplicity
Created September 26, 2016 18:50
Show Gist options
  • Save BrutalSimplicity/4370ea69a506214c9c800a6af51caaef to your computer and use it in GitHub Desktop.
Save BrutalSimplicity/4370ea69a506214c9c800a6af51caaef to your computer and use it in GitHub Desktop.
Methods for converting and object to/from a base-64 encoded string
public static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}
/// <summary>
/// Serializes and compresses an object, then returns the result as
/// a Base-64 encoded string.
/// </summary>
/// <param name="obj">object to compress</param>
/// <returns>Base-64 encoded string</returns>
public static string CompressObjectAsBase64(object obj)
{
BinaryFormatter formatter = new BinaryFormatter();
byte[] gZipBuffer;
byte[] compressedData;
using (var objectStream = new MemoryStream())
{
formatter.Serialize(objectStream, obj);
objectStream.Position = 0;
using (var outputStream = new MemoryStream())
{
using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress, true))
{
CopyTo(objectStream, gZipStream);
}
outputStream.Position = 0;
compressedData = new byte[outputStream.Length];
outputStream.Read(compressedData, 0, compressedData.Length);
}
gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(objectStream.Length), 0, gZipBuffer, 0, 4);
}
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompress Base64 string and then deserialize the raw bytes into
/// an object.
/// </summary>
/// <param name="compressedText">The compressed Base-64 string</param>
/// <returns>Deserialized Object</returns>
public static T DecompressObjectFromBase64<T>(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
BinaryFormatter formatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
MemoryStream objectStream;
T resultObject;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
using (objectStream = new MemoryStream())
{
CopyTo(gZipStream, objectStream);
objectStream.Position = 0;
resultObject = (T)formatter.Deserialize(objectStream);
}
}
return resultObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment