Gzip压缩和解压
程序员文章站
2022-03-20 10:18:02
/// /// 将传入字符串以GZip算法压缩后,返回Base64编码字符 /// /// 需要压缩的字符串 /// 压缩后的Base64编码的字符串 public string GZipCompressString(string rawString) { ... ......
/// <summary>
/// 将传入字符串以gzip算法压缩后,返回base64编码字符
/// </summary>
/// <param name="rawstring">需要压缩的字符串</param>
/// <returns>压缩后的base64编码的字符串</returns>
public string gzipcompressstring(string rawstring)
{
if (string.isnullorempty(rawstring) || rawstring.length == 0)
{
return "";
}
else
{
byte[] rawdata = system.text.encoding.utf8.getbytes(rawstring.tostring());
byte[] zippeddata = compress(rawdata);
return (string)(convert.tobase64string(zippeddata));
}
}
/// <summary>
/// gzip压缩
/// </summary>
/// <param name="rawdata"></param>
/// <returns></returns>
static byte[] compress(byte[] rawdata)
{
memorystream ms = new memorystream();
gzipstream compressedzipstream = new gzipstream(ms, compressionmode.compress, true);
compressedzipstream.write(rawdata, 0, rawdata.length);
compressedzipstream.close();
return ms.toarray();
}
/// <summary>
/// 将传入的二进制字符串资料以gzip算法解压缩
/// </summary>
/// <param name="zippedstring">经gzip压缩后的二进制字符串</param>
/// <returns>原始未压缩字符串</returns>
public static string gzipdecompressstring(string zippedstring)
{
if (string.isnullorempty(zippedstring) || zippedstring.length == 0)
{
return "";
}
else
{
byte[] zippeddata = convert.frombase64string(zippedstring.tostring());
using (var ms = new memorystream(zippeddata))
{
using (var zip = new gzipstream(ms, compressionmode.decompress))
{
using (var reader = new streamreader(zip))
{
return reader.readtoend();
}
}
}
}
}
下一篇: Photoshop滤镜简单制作光晕效果