GZip、Deflate压缩算法对应的C#压缩解压函数

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

GZip、Deflate压缩算法对应的C#压缩解压函数

///

/// GZip解压函数

///

///

///

public byte[] GZipDecompress(byte[] data)

{

using (MemoryStream stream = new MemoryStream())

{

using (GZipStream gZipStream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))

{

byte[] bytes = new byte[40960];

int n;

while ((n =

gZipStream.Read(bytes, 0, bytes.Length)) != 0)

{

stream.Write(bytes, 0, n);

}

gZipStream.Close();

}

return stream.ToArray();

}

}

///

/// GZip压缩函数

///

///

///

public byte[] GZipCompress(byte[] data)

{

using (MemoryStream stream = new MemoryStream())

{

using (GZipStream gZipStream = new GZipStream(stream, press))

{

gZipStream.Write(data, 0, data.Length);

gZipStream.Close();

}

return stream.ToArray();

}

}

///

/// Deflate解压函数

/// JS:var details = eval('(' +

utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法

///

///

///

public string DeflateDecompress(string strSource)

{

byte[] buffer =

Convert.FromBase64String(strSource);

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())

{

ms.Write(buffer, 0, buffer.Length);

ms.Position = 0;

using

(pression.DeflateStream stream = new

pression.DeflateStream(ms,

pressionMode.Decompress))

{

stream.Flush();

int nSize = 16 * 1024 +

256; //假设字符串不会超过16K

byte[] decompressBuffer = new byte[nSize];

int nSizeIncept =

stream.Read(decompressBuffer, 0, nSize);

stream.Close();

return

System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串

}

}

}

///

/// Deflate压缩函数

///

///

///

public string DeflateCompress(string strSource)

{

if (strSource == null || strSource.Length > 8 * 1024)

throw new System.ArgumentException("字符串为空或长度太大!");

byte[] buffer =

System.Text.Encoding.UTF8.GetBytes(strSource);

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())

{

using

(pression.DeflateStream stream = new

pression.DeflateStream(ms,

press, true))

{

stream.Write(buffer, 0, buffer.Length);

stream.Close();

}

byte[] compressedData = ms.ToArray();

ms.Close();

return

Convert.ToBase64String(compressedData); //将压缩后的byte[]转换为Base64String

}

}

相关文档
最新文档