본문 바로가기

Dev::DotNet/C#

GZipStream 을 이용한 문자열 압축


[Compress]

  using System;

  using System.Text;

  using System.IO;

  using System.IO.Compression;


  public String Zip(String decompressed)

        {

            string sResult = string.Empty;

            byte[] data = Encoding.UTF8.GetBytes(decompressed);

 

            using (MemoryStream input = new MemoryStream(data))

            {

                using (MemoryStream output = new MemoryStream())

                {

                    using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true))

                    {

                        input.CopyTo(gzip);

 

                        gzip.Close();

                        gzip.Dispose();

                    }

 

                    sResult = Convert.ToBase64String(output.ToArray());

 

                    output.Close();

                    output.Dispose();

                }

 

                input.Close();

                input.Dispose();

            }

 

            return sResult;

        }



[Decompress]

  public String UnZip(String compressed)

        {

            string sResult = string.Empty;

            byte[] data = Convert.FromBase64String(compressed);

 

            using (MemoryStream input = new MemoryStream(data))

            {

                using (GZipStream gzip = new GZipStream(input, CompressionMode.Decompress))

                {

                    using (MemoryStream output = new MemoryStream())

                    {

                        gzip.CopyTo(output);

 

                        sResult = Encoding.UTF8.GetString(output.ToArray());

 

                        output.Close();

                        output.Dispose();

                    }

 

                    gzip.Close();

                    gzip.Dispose();

                }

 

                input.Close();

                input.Dispose();

            }

 

            return sResult;

        }