Compression/Decompression string with C#

后端 未结 6 1930
情歌与酒
情歌与酒 2020-11-22 17:14

I am newbie in .net. I am doing compression and decompression string in C#. There is a XML and I am converting in string and after that I am doing compression and decompress

6条回答
  •  星月不相逢
    2020-11-22 17:37

    according to this snippet i use this code and it's working fine:

    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Text;
    
    namespace CompressString
    {
        internal static class StringCompressor
        {
            /// 
            /// Compresses the string.
            /// 
            /// The text.
            /// 
            public static string CompressString(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 Convert.ToBase64String(gZipBuffer);
            }
    
            /// 
            /// Decompresses the string.
            /// 
            /// The compressed text.
            /// 
            public static string DecompressString(string compressedText)
            {
                byte[] gZipBuffer = Convert.FromBase64String(compressedText);
                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);
                }
            }
        }
    }
    

提交回复
热议问题