如何使用SharpCompress的BZip2Stream压缩字符串? [英] How to use SharpCompress' BZip2Stream to compress a string?
本文介绍了如何使用SharpCompress的BZip2Stream压缩字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用SharpCompress的BZip2Stream压缩字符串(str)
,但是无法实现。以下是我到目前为止的代码,
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;
}
}
}
无论我通过什么字符串到 str
总是返回 BZh
。
No matter what string i pass to str
it always returns BZh
.
任何帮助
推荐答案
我相信您需要完成/关闭/刷新bzip2流,以确保所有压缩数据在从存储流中读取数据之前,将数据写入存储流。尝试:
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;
}
这篇关于如何使用SharpCompress的BZip2Stream压缩字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文