How to use SharpCompress' BZip2Stream to compress a string?

元气小坏坏 提交于 2019-12-08 12:24:49

问题


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:


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;
}


来源:https://stackoverflow.com/questions/19170796/how-to-use-sharpcompress-bzip2stream-to-compress-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!