How to compress and decompress byte array using GZip in C#

1 Answer

0 votes
using System;
using System.IO;
using System.IO.Compression;

public class Program
{
    static byte[] Decompress(byte[] byte_array) {
        using (var memoryStream = new MemoryStream(byte_array))
      
        using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
        
        using (var resultStream = new MemoryStream()) {
                gzipStream.CopyTo(resultStream);
                return resultStream.ToArray();
        }
    }
    
    static byte[] Compress(byte[] byte_array) {
        using (var memoryStream = new MemoryStream())
      
        using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress)) {
                gzipStream.Write(byte_array, 0, byte_array.Length);
                gzipStream.Close();
                return memoryStream.ToArray();
        }
    }
    
    public static void Main()
    {
        byte[] byte_array = {65, 66, 67, 90, 97, 98, 99, 122 };
        
        byte[] compressed = Compress(byte_array);
        Console.WriteLine(string.Join(" ", compressed));
        
        byte[] decompressed = Decompress(compressed);
        Console.WriteLine(string.Join(" ", decompressed));
    }
}
 
  
  
  
/*
run:
  
31 139 8 0 0 0 0 0 0 3 115 116 114 142 74 76 74 174 2 0 140 249 39 158 8 0 0 0
65 66 67 90 97 98 99 122

*/

 



answered Jul 28, 2023 by avibootz

Related questions

1 answer 185 views
1 answer 140 views
...