using System.IO; using System.IO.Compression; // Get the data to be compressed byte[] buffer = GetData(); // Create a memory stream to hold the compressed data using (var outputStream = new MemoryStream()) { // Create the GZipStream and set it to compress using (var gzipStream = new GZipStream(outputStream, CompressionMode.Compress)) { // Write the data to be compressed gzipStream.Write(buffer, 0, buffer.Length); } // Get the compressed data byte[] compressedData = outputStream.ToArray(); // Do something with the compressed data }
using System.IO; using System.IO.Compression; // Get the compressed data byte[] compressedData = GetCompressedData(); // Create a memory stream to hold the decompressed data using (var inputStream = new MemoryStream(compressedData)) using (var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress)) { int byteRead; // Create a buffer to hold the decompressed data byte[] buffer = new byte[4096]; // Decompress the data and write it to a MemoryStream using (var outputStream = new MemoryStream()) { while ((byteRead = gzipStream.ReadByte()) != -1) { outputStream.WriteByte((byte)byteRead); } // Get the decompressed data byte[] decompressedData = outputStream.ToArray(); // Do something with the decompressed data } }This code shows how to decompress data using the GZipStream class. It creates a byte array compressedData with the compressed data, creates a MemoryStream with the compressed data, and then creates a GZipStream and reads the compressed data from the stream. It reads the data one byte at a time using the ReadByte() method, writes it to a MemoryStream, and gets the decompressed data as a byte array. Finally, it does something with the decompressed data.