VB.NET文件ZIP压缩
1Public Function Decompress(ByVal algo As String, ByVal data() As Byte) As Byte()
2 Try
3 Dim sw As New Stopwatch
4 '---复制数据(压缩的)到ms---
5 Dim ms As New MemoryStream(data)
6 Dim zipStream As Stream = Nothing
7
8 '---开始秒表---
9 sw.Start()
10 '---使用存储在ms中的数据解压---
11
12 If algo = "Gzip" Then
13 zipStream = New GZipStream(ms, CompressionMode.Decompress)
14 ElseIf algo = "Deflate" Then
15 zipStream = New DeflateStream(ms, CompressionMode.Decompress, True)
16 End If
17
18 '---用来存储解压的数据---
19 Dim dc_data() As Byte
20
21 '---解压的数据存储于zipStream中;
22 '把它们提取到一个字节数组中---
23 dc_data = RetrieveBytesFromStream(zipStream, data.Length)
24
25 '---停止秒表---
26 sw.Stop()
27 lblMessage.Text = "Decompression completed. Time spent: " & sw.ElapsedMilliseconds & "ms" & _
28 ", Original size: " & dc_data.Length
29 Return dc_data
30 Catch ex As Exception
31 MsgBox(ex.ToString)
32 Return Nothing
33 End Try
34End Function
35
36Public Function RetrieveBytesFromStream( _
37ByVal stream As Stream, ByVal bytesblock As Integer) As Byte()
38
39 '---从一个流对象中检索字节---
40 Dim data() As Byte
41 Dim totalCount As Integer = 0
42 Try
43 While True
44
45 '---逐渐地增加数据字节数组-的大小--
46 ReDim Preserve data(totalCount + bytesblock)
47 Dim bytesRead As Integer = stream.Read(data, totalCount, bytesblock)
48 If bytesRead = 0 Then
49 Exit While
50 End If
51 totalCount += bytesRead
52 End While
53 '---确保字节数组正确包含提取的字节数---
54 ReDim Preserve data(totalCount - 1)
55 Return data
56 Catch ex As Exception
57 MsgBox(ex.ToString)
58 Return Nothing
59 End Try
60End Function
61
62
2 Try
3 Dim sw As New Stopwatch
4 '---复制数据(压缩的)到ms---
5 Dim ms As New MemoryStream(data)
6 Dim zipStream As Stream = Nothing
7
8 '---开始秒表---
9 sw.Start()
10 '---使用存储在ms中的数据解压---
11
12 If algo = "Gzip" Then
13 zipStream = New GZipStream(ms, CompressionMode.Decompress)
14 ElseIf algo = "Deflate" Then
15 zipStream = New DeflateStream(ms, CompressionMode.Decompress, True)
16 End If
17
18 '---用来存储解压的数据---
19 Dim dc_data() As Byte
20
21 '---解压的数据存储于zipStream中;
22 '把它们提取到一个字节数组中---
23 dc_data = RetrieveBytesFromStream(zipStream, data.Length)
24
25 '---停止秒表---
26 sw.Stop()
27 lblMessage.Text = "Decompression completed. Time spent: " & sw.ElapsedMilliseconds & "ms" & _
28 ", Original size: " & dc_data.Length
29 Return dc_data
30 Catch ex As Exception
31 MsgBox(ex.ToString)
32 Return Nothing
33 End Try
34End Function
35
36Public Function RetrieveBytesFromStream( _
37ByVal stream As Stream, ByVal bytesblock As Integer) As Byte()
38
39 '---从一个流对象中检索字节---
40 Dim data() As Byte
41 Dim totalCount As Integer = 0
42 Try
43 While True
44
45 '---逐渐地增加数据字节数组-的大小--
46 ReDim Preserve data(totalCount + bytesblock)
47 Dim bytesRead As Integer = stream.Read(data, totalCount, bytesblock)
48 If bytesRead = 0 Then
49 Exit While
50 End If
51 totalCount += bytesRead
52 End While
53 '---确保字节数组正确包含提取的字节数---
54 ReDim Preserve data(totalCount - 1)
55 Return data
56 Catch ex As Exception
57 MsgBox(ex.ToString)
58 Return Nothing
59 End Try
60End Function
61
62