GZipStream and ZLibStream classes not working.

May 1, 2015 at 8:03 AM
Edited May 1, 2015 at 8:04 AM
Hi, great work on this.

I'm having a problem with the GZipStream class. It is not compressing properly. On a certain input of about 56K in size, its returning a Stream of 10 bytes when compressed and 0 bytes when decompressed. I just want to know if this is a bug or if I'm using the class incorrectly.

Here is the code:-
    Public Function CompressBytes(ByVal bytes As Byte()) As Byte()
        Using ms As New MemoryStream(bytes)
            Using compressedMs As New MemoryStream
                Using gz As New GZipStream(compressedMs, CompressionMode.Compress)
                    Dim buffer As Byte() = New Byte(1000) {}

                    Dim bytesRead As Integer = ms.Read(buffer, 0, buffer.Length)

                    Do Until bytesRead = 0
                        gz.Write(buffer, 0, bytesRead)

                        bytesRead = ms.Read(buffer, 0, buffer.Length)
                    Loop

                    Return compressedMs.ToArray
                End Using
            End Using
        End Using
    End Function

    Public Function DecompressBytes(ByVal bytes As Byte()) As Byte()
        Using ms As New MemoryStream
            Using compressedMs As New MemoryStream(bytes)
                Using gz As New GZipStream(compressedMs, CompressionMode.Decompress)

                    Dim buffer As Byte() = New Byte(1000) {}

                    Dim bytesRead As Integer = gz.Read(buffer, 0, buffer.Length)

                    Do Until bytesRead = 0
                        ms.Write(buffer, 0, bytesRead)

                        bytesRead = gz.Read(buffer, 0, buffer.Length)
                    Loop


                    Return ms.ToArray

                End Using
            End Using
        End Using


    End Function
May 2, 2015 at 12:23 AM
Ok I solved it. It seems the GZipStream must be closed before reading the compressed stream for the compression to work properly.
Marked as answer by Niya on 5/1/2015 at 4:27 PM