Skip to main content

Compress and decompress bytes on-the-fly with C# functions, no need for external libraries.

//Downloaded from
//Visual C# Kicks - http://www.vcskicks.com/

using System;
using System.Text;
using System.Windows.Forms;
using System.IO.Compression;
using System.IO;

namespace CompressBytes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        byte[] compressed; // stored in bytes because decompression has to be done to bytes
                           // directly, trying to decompress a string will cause problems

        private void btnCompress_Click(object sender, EventArgs e)
        {
            compressed = ByteManager.CompressBytes(ByteManager.GetBytes(txtInput.Text));
            txtInput.Text = Encoding.ASCII.GetString(compressed);
        }

        private void btnDecompress_Click(object sender, EventArgs e)
        {
            if (compressed.Length != 0)
            {
                txtInput.Text = ByteManager.BytesToString(ByteManager.DecompressBytes(compressed));
                compressed = null;
            }
        }
    }

    internal class ByteManager
    {
        //Convert a string to bytes for compression/decompression
        public static byte[] GetBytes(string str)
        {
            return Encoding.ASCII.GetBytes(str);
        }

        //After compressing/decompressing bytes this turns them back to a string
        public static string BytesToString(byte[] bytes)
        {
            return Encoding.ASCII.GetString(bytes);
        }

        public static byte[] CompressBytes(byte[] bytes)
        {
            //Simply write the bytes to memory using the .Net compression stream
            MemoryStream output = new MemoryStream();
            GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);
            gzip.Write(bytes, 0, bytes.Length);
            gzip.Close();
            return output.ToArray();
        }

        public static byte[] DecompressBytes(byte[] bytes)
        {
            //Use the .Net decompression stream in memory
            MemoryStream input = new MemoryStream();
            input.Write(bytes, 0, bytes.Length);
            input.Position = 0;

            GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);
            MemoryStream output = new MemoryStream();

            byte[] buff = new byte[64]; //Compressed bytes are read in 64 bytes at a time
            int read = -1;
            read = gzip.Read(buff, 0, buff.Length);
            while (read > 0)
            {
                output.Write(buff, 0, read);
                read = gzip.Read(buff, 0, buff.Length);
            }

            gzip.Close();

            return output.ToArray();
        }
    }
}