Skip to content

Instantly share code, notes, and snippets.

@benerdin
Created January 14, 2014 22:27
Show Gist options
  • Select an option

  • Save benerdin/8427149 to your computer and use it in GitHub Desktop.

Select an option

Save benerdin/8427149 to your computer and use it in GitHub Desktop.
Extension methods for compressing and decompressing a string using GZipStream.
/// <summary>
/// Encapsulates extension methods related to compression.
/// </summary>
public static class CompressionExtensions
{
/// <summary>
/// Compresses <paramref name="uncompressedString"/> and returns the result.
/// </summary>
/// <param name="uncompressedString">An uncompressed string.</param>
/// <returns>A base-64 string.</returns>
public static string CompressToGZipString(this string uncompressedString)
{
using (var outputStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(outputStream, CompressionMode.Compress))
{
// Write uncompressed string to the gzip stream which
// writes to the underlying memory stream.
using (var writer = new StreamWriter(gzipStream))
{
writer.Write(uncompressedString);
}
}
// Return a base-64 string from the byte array
// in the memory stream.
return Convert.ToBase64String(
outputStream.ToArray()
);
}
}
/// <summary>
/// Decompresses <paramref name="compressedBase64String"/> and returns the result.
/// </summary>
/// <param name="compressedBase64String">A compressed base-64 string.</param>
/// <returns>A string.</returns>
public static string DecompressFromGZipString(this string compressedBase64String)
{
// Convert the base-64 string to a byte array.
var bytes = Convert.FromBase64String(compressedBase64String);
using (var ms = new MemoryStream(bytes))
{
using (var gs = new GZipStream(ms, CompressionMode.Decompress))
{
// Read from the gzip stream which reads
// from the underlying memory stream.
using (var reader = new StreamReader(gs))
{
return reader.ReadToEnd();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment