//using System.IO;
//using System.IO.Compression;
/// <summary>
/// GZipStream压缩字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public Stream GZipCompress(string str)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
MemoryStream msReturn;
using (MemoryStream msTemp = new MemoryStream())
{
using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, [color=Red]true[/color]))
{
gz.Write(buffer, 0, buffer.Length);
[color=Red]gz.Close();[/color]
msReturn = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length);
}
}
return msReturn;
}
/// <summary>
/// GZipStream解压字符串
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public string GZipDecompress(Stream stream)
{
byte[] buffer = new byte[100];
int length = 0;
using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
}
return System.Text.Encoding.UTF8.GetString(msTemp.ToArray());
}
}
}说明
·压缩时GZipStream构造函数第三个参数一定要设置为true,并且一定要先调用Close再来复制,否则不能正常解压(测试发现调用Close后会追加几字节内容);
·解压时直接使用Read方法读取内容,不能调用GZipStream实例的Length等属性,否则会出错:System.NotSupportedException: 不支持此操作;
评论(0)
暂无评论。