Calling a GZIP compression method should be simple. We develop a method that compresses any byte
array in memory and returns that GZIP data.
We implement a static
compression method. We can handle GZIP in older .NET versions, and Brotli in newer versions like .NET 5.
Please notice the namespaces at the top. First, a new string
is created with 10,000 X characters. This is converted to a byte
array in GetBytes
.
Compress()
creates a MemoryStream
and GZipStream
. It then writes to the GZipStream
, which uses MemoryStream
as a buffer.MemoryStream
is converted to a byte
array. Finally the File.WriteAllBytes
method outputs the data to the file compress.gz
.compress.gz
file. The result was the original 10,000 character string
.using System; using System.IO; using System.IO.Compression; using System.Text; class Program { static void Main() { // Convert 10000 character string to byte array. byte[] text = Encoding.ASCII.GetBytes(new string('X', 10000)); // Use compress method. byte[] compress = Compress(text); // Write compressed data. File.WriteAllBytes(@"C:\programs\compress.gz", compress); Console.WriteLine("DONE"); } /// <summary> /// Compresses byte array to new byte array. /// </summary> public static byte[] Compress(byte[] raw) { using (MemoryStream memory = new MemoryStream()) { using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true)) { gzip.Write(raw, 0, raw.Length); } return memory.ToArray(); } } }DONE
This code compressed both in Brotli with BrotliStream
, and GZIP with GZipStream
. Brotli is a newer compression format that works better than GZIP on web pages.
byte
arrays returned to disk. These are the final compressed files.BrotliStream
can only be used on newer versions of .NET, as it is a newer compression format.using System; using System.IO; using System.IO.Compression; class Program { static void Main() { // Part 1: read in file. var data = File.ReadAllBytes(@"C:\stage-perls\_sitemap"); // Part 2: write out compressed files. File.WriteAllBytes(@"C:\programs\brotli-out", CompressBrotli(data)); File.WriteAllBytes(@"C:\programs\gzip-out", CompressGZip(data)); Console.WriteLine("DONE"); } static byte[] CompressBrotli(byte[] raw) { using (MemoryStream memory = new MemoryStream()) { using (BrotliStream brotli = new BrotliStream(memory, CompressionLevel.Optimal)) { brotli.Write(raw, 0, raw.Length); } return memory.ToArray(); } } static byte[] CompressGZip(byte[] raw) { using (MemoryStream memory = new MemoryStream()) { using (GZipStream gzip = new GZipStream(memory, CompressionLevel.Optimal)) { gzip.Write(raw, 0, raw.Length); } return memory.ToArray(); } } }DONE
We wrote a method that effectively compresses any data stored in a byte
array in memory. GZIP and Brotli can be used to compress the data.