28 Mart 2019

C# String Compress and Uncompress

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            var xmlContent = File.ReadAllText("CompressExample.txt");
            Console.WriteLine($"Plain XML Text Size {xmlContent.Length}");
            var compressedText = xmlContent.Zip();
            Console.WriteLine($"Plain XML Text Size {compressedText.Length}");
            Console.WriteLine($"Uncompressed == Plain {compressedText.Unzip() == xmlContent}");
            Console.ReadKey();

        }

    }
    public static class StringExtensions
    {
        public static string Zip(this string str)
        {
            var bytes = Encoding.UTF8.GetBytes(str);
            var compressedBytes = ComporessionUtils.Zip(bytes);
            var base64 = Convert.ToBase64String(compressedBytes);
            return base64;
        }

        public static string Unzip(this string compressedBase64String)
        {
            var compressedBytes = Convert.FromBase64String(compressedBase64String);
            var uncompressedBytes = ComporessionUtils.Unzip(compressedBytes);
            var result = Encoding.UTF8.GetString(uncompressedBytes);
            return result;
        }
    }
    public class ComporessionUtils
    {
        public static void CopyTo(Stream src, Stream dest)
        {
            var bytes = new byte[4096];

            int cnt;

            while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
            {
                dest.Write(bytes, 0, cnt);
            }
        }



        public static byte[] Zip(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                {
                    CopyTo(msi, gs);
                }
                return mso.ToArray();
            }
        }

        public static byte[] Unzip(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                {
                    CopyTo(gs, mso);
                }

                return mso.ToArray();
            }
        }
    }
}