Imports System.IO ' for Stream object
Imports System.IO.Compression ' for DeflateStream and GZipStream
Public Enum eCompressMethod As Byte
Deflate = 1
Gzip = 2
End Enum
Public Class CompressWrapper
Const CHUNKSIZE As Integer = 4096
Public Shared Sub Compress(ByVal input As Stream, ByVal output As Stream, _
ByVal CompressMethod As eCompressMethod)
Dim zipStream As Stream = Nothing 'The zip stream we will use for compression
Try
Select Case CompressMethod
Case eCompressMethod.Deflate
zipStream = New DeflateStream(output, CompressionMode.Compress)
Case eCompressMethod.Gzip
zipStream = New GZipStream(output, CompressionMode.Compress)
End Select
'Compress the original bytes array
CopyStream(input, zipStream)
Catch ex As Exception
Throw ex
Finally
If Not zipStream Is Nothing Then
zipStream.Close()
zipStream = Nothing
End If
End Try
End Sub
Public Shared Sub Decompress(ByVal input As Stream, ByVal output As Stream, ByVal
CompressMethod As eCompressMethod)
Dim zipStream As Stream = Nothing 'The zip stream we will use for decompression
Try
Select Case CompressMethod
Case eCompressMethod.Deflate
zipStream = New DeflateStream(input, CompressionMode.Decompress)
Case eCompressMethod.Gzip
zipStream = New GZipStream(input, CompressionMode.Decompress)
End Select
'DeCompress
CopyStream(zipStream, output)
Catch ex As Exception
Throw ex
Finally
If Not zipStream Is Nothing Then
zipStream.Close()
zipStream = Nothing
End If
End Try
End Sub
Private Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
Dim bytes(CHUNKSIZE) As Byte
Dim n As Integer
While True
n = input.Read(bytes, 0, bytes.Length)
If n = 0 Then Exit Sub
output.Write(bytes, 0, n)
End While
End Sub
End Class