我正在尝试使用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
。
非常感谢任何帮助!
答案 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;
}