CSharpFeeds - All your C# feeds in one place.

Sponsors

Wednesday, March 07, 2007

Compress and decompress strings in C#

by post@madskristensen.dk (Mads Kristensen) via .NET Slave on 3/7/2007 11:25:35 PM

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;

publicstaticstring 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 =newbyte[ms.Length];
 ms.Read(compressed, 0, compressed.Length);

 byte[] gzBuffer =newbyte[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);
}

publicstaticstring 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 =newbyte[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.

email it!bookmark it!digg it!

Original Post: Compress and decompress strings in C#

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us