Compression/Decompression string with C#

后端 未结 6 1911
情歌与酒
情歌与酒 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:46

    This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:

    public static class CompressionExtensions
    {
        public static async Task> Zip(this object obj)
        {
            byte[] bytes = obj.Serialize();
    
            using (MemoryStream msi = new MemoryStream(bytes))
            using (MemoryStream mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                    await msi.CopyToAsync(gs);
    
                return mso.ToArray().AsEnumerable();
            }
        }
    
        public static async Task Unzip(this byte[] bytes)
        {
            using (MemoryStream msi = new MemoryStream(bytes))
            using (MemoryStream mso = new MemoryStream())
            {
                using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                {
                    // Sync example:
                    //gs.CopyTo(mso);
    
                    // Async way (take care of using async keyword on the method definition)
                    await gs.CopyToAsync(mso);
                }
    
                return mso.ToArray().Deserialize();
            }
        }
    }
    
    public static class SerializerExtensions
    {
        public static byte[] Serialize(this T objectToWrite)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, objectToWrite);
    
                return stream.GetBuffer();
            }
        }
    
        public static async Task _Deserialize(this byte[] arr)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                await stream.WriteAsync(arr, 0, arr.Length);
                stream.Position = 0;
    
                return (T)binaryFormatter.Deserialize(stream);
            }
        }
    
        public static async Task Deserialize(this byte[] arr)
        {
            object obj = await arr._Deserialize();
            return obj;
        }
    }
    
    
    

    With this you can serialize everything BinaryFormatter supports, instead only of strings.

    Edit:

    In case, you need take care of Encoding, you could just use Convert.ToBase64String(byte[])...

    Take a look at this answer if you need an example!

    提交回复
    热议问题