0

I am trying to compress a string (str) using SharpCompress' BZip2Stream but unable to achieve it. Following is the code I have so far,

public static string Compress(string str)
{
    var data = Encoding.UTF8.GetBytes(str);
    using (MemoryStream stream = new MemoryStream())
    {
        using (BZip2Stream zip = new BZip2Stream(stream, SharpCompress.Compressor.CompressionMode.Compress))
        {
            zip.Write(data, 0, data.Length);
            var compressed = Encoding.UTF8.GetString(stream.ToArray());
            return compressed;
        }
    }
}

No matter what string i pass to str it always returns BZh.

Any help is greatly appreciated!

  • What are you expecting the program to do? What is it doing now? – Multimedia Mike Oct 04 '13 at 05:26
  • I am trying to compress a string say 'string to compress' or 'abcxyz' no matter what the value of `str` is it always returns a byte array of length 3 and when converted to string using Encoding.UTF8.GetString(bytes) the value of the string is always `BZh` –  Oct 04 '13 at 16:41

1 Answers1

0

I believe you need to finalize/close/flush the bzip2 stream in order to make sure all compressed data is written to the memory stream prior to reading data from the memory stream. Try:

using (MemoryMemoryStream stream = new MemoryStream())
{
    using (BZip2Stream zip = new BZip2Stream(stream, SharpCompress.Compressor.CompressionMode.Compress))
    {
        zip.Write(data, 0, data.Length);
        zip.Close();
    }
    var compressed = Encoding.UTF8.GetString(stream.ToArray());
    return compressed;
}
David Nordvall
  • 12,404
  • 6
  • 32
  • 52