How to use SharpCompress' BZip2Stream to compr

2019-06-13 06:28发布

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!

1条回答
手持菜刀,她持情操
2楼-- · 2019-06-13 06:51

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;
}
查看更多
登录 后发表回答