| 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. |