How to compress and decompress byte array using GZip in VB.NET

1 Answer

0 votes
Imports System
Imports System.IO
Imports System.IO.Compression

Public Class Program
    Private Shared Function Decompress(ByVal byte_array As Byte()) As Byte()
        Using memoryStream = New MemoryStream(byte_array)
            Using gzipStream = New GZipStream(memoryStream, CompressionMode.Decompress)
                Using resultStream = New MemoryStream()
                    gzipStream.CopyTo(resultStream)
                    Return resultStream.ToArray()
                End Using
            End Using
        End Using
    End Function

    Private Shared Function Compress(ByVal byte_array As Byte()) As Byte()
        Using memoryStream = New MemoryStream()
            Using gzipStream = New GZipStream(memoryStream, CompressionMode.Compress)
                gzipStream.Write(byte_array, 0, byte_array.Length)
                gzipStream.Close()
                Return memoryStream.ToArray()
            End Using
        End Using
    End Function

    Public Shared Sub Main()
        Dim byte_array As Byte() = {65, 66, 67, 90, 97, 98, 99, 122}

        Dim compressed As Byte() = Compress(byte_array)
        Console.WriteLine(String.Join(" ", compressed))
        
		Dim decompressed As Byte() = Decompress(compressed)
        Console.WriteLine(String.Join(" ", decompressed))
    End Sub
End Class





' run:
'
' 31 139 8 0 0 0 0 0 4 0 115 116 114 142 74 76 74 174 2 0 140 249 39 158 8 0 0 0
' 65 66 67 90 97 98 99 122
'

 



answered Jul 28, 2023 by avibootz
...