如何使用SharpCompress的'BZip2Stream来压缩字符串?

时间:2013-10-03 23:29:10

标签: c# compression zip bzip2 sharpcompress

我正在尝试使用SharpCompress'BZip2Stream压缩字符串(str)但无法实现它。以下是我到目前为止的代码,

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

无论我传递给str的字符串,它总是返回BZh

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我认为您需要完成/关闭/刷新bzip2流,以确保在从内存流中读取数据之前将所有压缩数据写入内存流。尝试:

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