Compress and decompress strings in .NET
I recently had the need to store strings in a database in a compressed format. I wanted to store some potentially long strings in a SQL server image type column. After some time searching the internet for solutions I came across a neat .NET namespace called System.IO.Compression which looked like it could be the answer to my problem…
Here is the helper class I wrote to perform compression and decompression:
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace Utility
{
public static class CompressionHelper
{
public static byte[] CompressText(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream compressedStream = new MemoryStream();
DeflateStream compressedZipStream = new DeflateStream(compressedStream, CompressionMode.Compress, true);
compressedZipStream.Write(buffer, 0, buffer.Length);
compressedZipStream.Close();
compressedStream.Position = 0;
byte[] compressed = new byte[compressedStream.Length];
compressedStream.Read(compressed, 0, (int)compressedStream.Length);
return compressed;
}
public static string DecompressText(byte[] compressed)
{
MemoryStream compressedStream = new MemoryStream(compressed);
DeflateStream zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress);
List<byte> bytes = new List<byte>();
int offset = 0;
while (true)
{
byte[] temp = new byte[offset + 100];
int bytesRead = zipStream.Read(temp, offset, 100);
if (bytesRead == 0)
{
break;
}
for (int i = offset; i < offset + bytesRead; i++)
{
bytes.Add(temp[i]);
}
offset += bytesRead;
}
return Encoding.UTF8.GetString(bytes.ToArray());
}
}
}
Of course you could argue that this class is too specialised right now. It served my purpose well, but you could take and return byte arrays or streams as parameters to make it more general and re-use friendly.
Please let me know if you find any bugs…
Enjoy!
Leave a Comment