VB进行GZIP解压的,DLL是系统的,如果没有
1 Option Explicit 2 'GZIP API 3 '-------------------------------------------------- 4 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) 5 Private Declare Function InitDecompression Lib "gzip.dll" () As Long 6 Private Declare Function CreateDecompression Lib "gzip.dll" (ByRef context As Long, ByVal Flags As Long) As Long 7 Private Declare Function DestroyDecompression Lib "gzip.dll" (ByRef context As Long) As Long 8 Private Declare Function Decompress Lib "gzip.dll" (ByVal context As Long, inBytes As Any, ByVal input_size As Long, outBytes As Any, ByVal output_size As Long, ByRef input_used As Long, ByRef output_used As Long) As Long 9 '=============================================================10 '2012-10-511 'gzip解压,返回值表示是否成功,如果成功,解压结果通过址参回传12 '=============================================================13 Public Function UnGzip(ByRef arrBit() As Byte) As Boolean14 On Error GoTo errline15 Dim SourceSize As Long16 Dim buffer() As Byte17 Dim lReturn As Long18 Dim outUsed As Long19 Dim inUsed As Long20 Dim chandle As Long21 If arrBit(0) <> &H1F Or arrBit(1) <> &H8B Or arrBit(2) <> &H8 Then22 Exit Function '不是GZIP数据的字节流23 End If24 '获取原始长度25 'GZIP格式的最后4个字节表示的是原始长度26 '与最后4个字节相邻的4字节是CRC32位校验,用于比对是否和原数据匹配27 lReturn = UBound(arrBit) - 328 CopyMemory SourceSize, arrBit(lReturn), 429 '重点在这里,网上有些代码计算解压存放空间用了一些奇怪的公式30 '如:L = 压缩大小 * (1 + 0.01) + 1231 '不知道怎么得到的,用这种方式偶尔会报错...32 '这里的判断是因为:(维基)一个压缩数据集包含一系列的block(块),只要未压缩数据大小不超过65535字节,块的大小是任意的。33 'GZIP基本头是10字节34 If SourceSize > 65535 Or SourceSize < 10 Then35 '测试用,申请100KB空间尝试一下36 'SourceSize = 10240037 Exit Function38 Else39 SourceSize = SourceSize + 140 End If41 ReDim buffer(SourceSize) As Byte42 '创建解压缩进程43 InitDecompression44 CreateDecompression chandle, 1 '创建45 '解压缩数据46 Decompress ByVal chandle, arrBit(0), UBound(arrBit) + 1, buffer(0), SourceSize + 1, inUsed, outUsed47 If outUsed <> 0 Then48 DestroyDecompression chandle49 ReDim arrBit(outUsed - 1)50 CopyMemory arrBit(0), buffer(0), outUsed51 UnGzip = True52 End If53 Exit Function54 errline:55 End Function
C#进行GZIP压缩和解压,参考
1 public static byte[] GZipCompress(byte[] buffer) 2 { 3 using (MemoryStream ms = new MemoryStream()) 4 { 5 GZipStream Compress = new GZipStream(ms, CompressionMode.Compress); 6 Compress.Write(buffer, 0, buffer.Length); 7 Compress.Close(); 8 return ms.ToArray(); 9 }10 }11 public static byte[] GZipDecompress(byte[] buffer)12 {13 using (MemoryStream tempMs = new MemoryStream())14 {15 using (MemoryStream ms = new MemoryStream(buffer))16 {17 GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);18 Decompress.CopyTo(tempMs);19 Decompress.Close();20 return tempMs.ToArray();21 }22 }23 }