Skip to content

Instantly share code, notes, and snippets.

@ijat
Created December 21, 2020 15:36
Show Gist options
  • Save ijat/f1ff6e85ba1222cfbd624d4e849d67e1 to your computer and use it in GitHub Desktop.
Save ijat/f1ff6e85ba1222cfbd624d4e849d67e1 to your computer and use it in GitHub Desktop.
Dotnet string / text compression and decompression extension
public static class StringCompressionExtension
{
/// <summary>
/// Compresses the string to bytes array.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static byte[] Compress(this string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return gZipBuffer;
}
/// <summary>
/// Decompresses the string from bytes array.
/// </summary>
/// <param name="encodedBytes"></param>
/// <returns></returns>
public static string Decompress(this byte[] encodedBytes)
{
byte[] gZipBuffer = encodedBytes;
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;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
@ijat
Copy link
Author

ijat commented Dec 21, 2020

How to use?

string myText = "hello world";
byte[] compressedBytes = myText.Compress();
string decompressedText = compressedBytes.Decompress();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment