SHARE
TWEET

String Compression

ForeverZer0 May 9th, 2014 265 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Text;
  5.  
  6. namespace CompressString
  7. {
  8.     internal static class StringCompressor
  9.     {
  10.         /// <summary>
  11.         /// Compresses the string.
  12.         /// </summary>
  13.         /// <param name="text">The text.</param>
  14.         /// <returns></returns>
  15.         public static string CompressString(string text)
  16.         {
  17.             byte[] buffer = Encoding.UTF8.GetBytes(text);
  18.             var memoryStream = new MemoryStream();
  19.             using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
  20.             {
  21.                 gZipStream.Write(buffer, 0, buffer.Length);
  22.             }
  23.  
  24.             memoryStream.Position = 0;
  25.  
  26.             var compressedData = new byte[memoryStream.Length];
  27.             memoryStream.Read(compressedData, 0, compressedData.Length);
  28.  
  29.             var gZipBuffer = new byte[compressedData.Length + 4];
  30.             Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
  31.             Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
  32.             return Convert.ToBase64String(gZipBuffer);
  33.         }
  34.  
  35.         /// <summary>
  36.         /// Decompresses the string.
  37.         /// </summary>
  38.         /// <param name="compressedText">The compressed text.</param>
  39.         /// <returns></returns>
  40.         public static string DecompressString(string compressedText)
  41.         {
  42.             byte[] gZipBuffer = Convert.FromBase64String(compressedText);
  43.             using (var memoryStream = new MemoryStream())
  44.             {
  45.                 int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
  46.                 memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
  47.  
  48.                 var buffer = new byte[dataLength];
  49.  
  50.                 memoryStream.Position = 0;
  51.                 using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
  52.                 {
  53.                     gZipStream.Read(buffer, 0, buffer.Length);
  54.                 }
  55.  
  56.                 return Encoding.UTF8.GetString(buffer);
  57.             }
  58.         }
  59.     }
  60. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top