C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Compressing files in memory in this way is faster than using an external program (7-Zip) but the compression ratio is poorer.
7-Zip ExecutableCompress: This method creates MemoryStream and GZipStream instances and then writes the GZipStream, which uses the MemoryStream as a buffer.
Then: The MemoryStream is converted to a byte array. Finally the File.WriteAllBytes method outputs the data to the file compress.gz.
Convert String, Byte ArrayMemoryStreamC# program that implements Compress method
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("compress.gz", compress);
    }
    /// <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();
        }
    }
}
Output
1. compress.gz is written to the disk at 213 bytes.
2. Decompress compress.gz and it is 10000 bytes.