C# .NET: Compression and Decompression

11/22/2013 10:00:21 PM

Use the built in .NET Framework compression/decompression abilities. The code uses GZip compression.

//using statements
using System;
using System.Text;
using System.IO;
using System.IO.Compression;

.....

public static string CompressString(string value)
{
	if (string.IsNullOrEmpty(value))
	{
		return value;
	}

	var bytes = Encoding.Unicode.GetBytes(value);
	using (var msi = new MemoryStream(bytes))
	{
		using (var mso = new MemoryStream())
		{
			using (var gs = new GZipStream(mso, CompressionMode.Compress))
			{
				msi.CopyTo(gs);
			}
			return Convert.ToBase64String(mso.ToArray());
		}
	}
}


public static string DecompressString(string value)
{
	if (string.IsNullOrEmpty(value))
	{
		return value;
	}

	var bytes = Convert.FromBase64String(value);
	using (var msi = new MemoryStream(bytes))
	{
		using (var mso = new MemoryStream())
		{
			using (var gs = new GZipStream(msi, CompressionMode.Decompress))
			{
				gs.CopyTo(mso);
			}
			return Encoding.Unicode.GetString(mso.ToArray());
		}
	}
}