Compress and decompress strings in C#

CK CK 3788 
Created at
Updated at  
972 0 0

GZipStream is a class in C# that provides a way to compress and decompress data using the GZIP algorithm. It acts as a wrapper around a stream, allowing you to read or write compressed data to and from the stream. When used for compression, it takes an input stream of uncompressed data and writes compressed data to an output stream. Conversely, when used for decompression, it takes an input stream of compressed data and writes uncompressed data to an output stream. GZipStream is commonly used to reduce the size of files, improve network transmission efficiency, and optimize storage space. 

The Convert.ToBase64String method in C# is used to convert a byte array into its Base64 encoded string representation. This encoding process transforms binary data into a textual format that can be safely transmitted over networks or stored in text files. The resulting Base64 string consists of characters from the ASCII alphabet (A-Z, a-z, 0-9), plus the symbols '+' and '/'. This ensures compatibility and readability across various systems.

A couple of days ago, I had to store some very big strings in an XML file. To keep the file size down I wanted to compress the strings using a GZipStream and then decompress them later when needed.

I modified the methods from Papenoo pa so they handled strings in stead of byte arrays.
 

using System.IO.Compression;
using System.Text;
using System.IO;

public static string Compress(string text)
{
 byte[] buffer = Encoding.UTF8.GetBytes(text);
 MemoryStream ms = new MemoryStream();
 using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
 {
  zip.Write(buffer, 0, buffer.Length);
 }

 ms.Position = 0;
 MemoryStream outStream = new MemoryStream();

 byte[] compressed = new byte[ms.Length];
 ms.Read(compressed, 0, compressed.Length);

 byte[] gzBuffer = new byte[compressed.Length + 4];
 System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
 System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
 return Convert.ToBase64String (gzBuffer);
}

public static string Decompress(string compressedText)
{
 byte[] gzBuffer = Convert.FromBase64String(compressedText);
 using (MemoryStream ms = new MemoryStream())
 {
  int msgLength = BitConverter.ToInt32(gzBuffer, 0);
  ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

  byte[] buffer = new byte[msgLength];

  ms.Position = 0;
  using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
  {
   zip.Read(buffer, 0, buffer.Length);
  }

  return Encoding.UTF8.GetString(buffer);
 } 
}


The strings need to be longer than 3-400 characters; otherwise the compression rate is not good enough.
 

Tags Base64Encode EnableVisualStyles How to convert UTF8 string to Base64 string UTF8Decode UTF8Encode Facebook X
Comments 0
Similar posts
  1. Base64 Encoding/Decoding function for Delphi
    1,153
  1. URL Encode, Decode function for MFC
    605
  2. How to load HTML resource on MFC ?
    841
  3. How to get GM Time as String ?
    422
  4. Makefile to automate the build process for C++
    279
  5. Finding process name on OS
    408
  6. Convert System.DateTime to UNIX timestamp
    381
  7. Retrieve system information
    495
  8. How to call SetTimer function on MFC CDialog class ?
    651
  9. How to rename(change file name) in C# ?
    1,075
  10. Find Files in certain directory
    926
  11. Implementing C#'s foreach loop in Delphi 8
    459
  12. How to detect resource leaks in a Form
    939
  13. The best way to enable and disable buttons, menu items and toolbar buttons
    667
  14. How to exit from a console application
    811
  15. How to restrict a program to a single instance
    729
  16. Graphics in C# - Irregular Forms
    908
  17. Extracting the Country from IP Address
    468
  18. How to run shell command by MFC ?
    436
  19. Binary Search Sample Code
    405
  20. Double Linked List based in C++
    796
  21. String Replace Function For C#
    1,547
  22. How to print character in C# by ASCII code
    477
  23. MFC based World Wide Web HTTP Server Source Code
    459
  24. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    472
  25. UDP Send and Receive Using CAsyncSocket
    1,204
  26. Using the shell to receive notification of removable media being inserted or removed
    681
  27. Adding Custom Paper Sizes To Named Printers
    647
  28. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  29. A Customizable Printing Text Class
    432
  30. Simplified .NET Printing In C#
    692
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    245
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260