C#自定义字符串压缩和解压缩源码库

536 阅读1分钟
如下的内容是关于C#自定义字符串压缩和解压缩库的内容。

class ZipLib
    {
        public static string Zip(string value)
        {
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
                System.IO.Compression.CompressionMode.Compress);

            sw.Write(byteArray, 0, byteArray.Length);
            sw.Close();

            byteArray = ms.ToArray();
            System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
            foreach (byte item in byteArray)
            {
                sB.Append((char)item);
            }
            ms.Close();
            sw.Dispose();
            ms.Dispose();
            return sB.ToString();
        }

        public static string UnZip(string value)
        {
            byte[] byteArray = new byte[value.Length];
            int indexBA = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[indexBA++] = (byte)item;
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
            System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
                System.IO.Compression.CompressionMode.Decompress);

            byteArray = new byte[byteArray.Length];

            int rByte = sr.Read(byteArray, 0, byteArray.Length);

            System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
            for (int i = 0; i < rByte; i++)
            {
                sB.Append((char)byteArray[i]);
            }
            sr.Close();
            ms.Close();
            sr.Dispose();
            ms.Dispose();
            return sB.ToString();
        }
    }


                                
                        
                                
代码使用方法
                                
                        
                                

string str_org="aaaaaaaaaabbbbbbbbbbbbcccccccccdddddddd";
            string str_comp = ZipLib.Zip(str_org);
            Console.WriteLine("str_comp:" + str_comp);

            string str_uncomp = ZipLib.UnZip(str_comp);
            Console.WriteLine("str_uncomp:" + str_uncomp);


            Console.ReadLine();