String Compression

6/2/2021

Bandwidth on large text can be significantly improved with basic string compression. The System.IO.Compression namespace includes a rather easy to use compression algorithm. Here is an example implementation:

    public static class StringCompression
    {
        public static byte[] ToGzip(string value)
        {
            var bytes = Encoding.Unicode.GetBytes(value);
            using (var inputStream = new MemoryStream(bytes))
            using (var outputStream = new MemoryStream())
            using (var stream = new GZipStream(outputStream, CompressionMode.Compress))
            {
                inputStream.CopyTo(stream);
                // Use Close instead of Flush here:
                stream.Close();
                byte[] output = outputStream.ToArray();
                return output;
            }
        }

        public static string FromGzip(byte[] bytes)
        {
            using (var input = new MemoryStream(bytes))
            using (var output = new MemoryStream())
            using (var stream = new GZipStream(input, CompressionMode.Decompress))
            {
                stream.CopyTo(output);
                stream.Flush();
                return Encoding.Unicode.GetString(output.ToArray());
            }
        }
    }

Here is a simple Unit Test demonstrating its use:

    [TestMethod]
    public void StringCompressionTest()
    {
        var original = System.IO.File.ReadAllText(@"C:\LargeFile.txt");
        byte[] compressed = StringCompression.ToGzip(original);
        string uncompressed = StringCompression.FromGzip(compressed);
        Assert.AreEqual(original, uncompressed);
    }

Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET
  • T-SQL
  • HTML/CSS
  • JavaScript/jQuery
  • .NET 8
  • ASP.NET/MVC
  • Xamarin/MAUI
  • WPF
  • Windows 11
  • SQL Server 20xx
  • Android
  • XBox
  • Arduino
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking