1

I'm trying to compress a string, store it in a variable, and then decompress it (using GZipStream), but nothing I try seems to work and everything I'm browsing doesn't help. The string is compressed properly, but then I just can't decompress it back. In this example, the variable DecompressedString should be "Hello world!" but it's just empty.

To be clear, the function that compress the string "Hello world!" works fine, and the end result is "H4sIAAAAAAAEAA==". My problem is that i need to store the compressed string in a string variable, and eventually decompress it back. I'm trying to decompress the string "H4sIAAAAAAAEAA==" back into "Hello world!", but the end result of the decompression is an empty string.

Dim InputString As String = "Hello world!"
Dim CompressedString As String = ""
Dim DecompressedString As String = ""

Dim inputBytes() As Byte = Encoding.UTF8.GetBytes(InputString)

Using outputStream As New MemoryStream
    Using gZipStream As New GZipStream(outputStream, CompressionMode.Compress)
        gZipStream.Write(inputBytes, 0, inputBytes.Length)

        Dim outputBytes = outputStream.ToArray()

        CompressedString = Convert.ToBase64String(outputBytes)
        MsgBox(CompressedString) 'At this point, CompressedString="H4sIAAAAAAAEAA=="
    End Using
End Using

inputBytes = Convert.FromBase64String(CompressedString)

Using inputStream As New MemoryStream(inputBytes)
    Using gZipStream As New GZipStream(inputStream, CompressionMode.Decompress)
        Using streamReader As New StreamReader(gZipStream)
            DecompressedString = streamReader.ReadToEnd()
            MsgBox(DecompressedString)
        End Using
    End Using
End Using
LPCarlos
  • 15
  • 3
  • 3
    Does this answer your question? [.NET GZipStream decompress producing empty stream](https://stackoverflow.com/questions/11915612/net-gzipstream-decompress-producing-empty-stream) – GSerg Dec 16 '21 at 18:22
  • 1
    Have you checked what `outputBytes` actually contains, at that point? Just add `gZipStream.Flush()` before `Dim outputBytes = outputStream.ToArray()` -- Your decompressed string is empty because the compressed string is really empty (or, it doesn't contain your source text). – Jimi Dec 16 '21 at 18:53
  • @Jimi outputBytes.length=10. Everything is OK up to MsgBox(CompressedString), at the string stored="H4sIAAAAAAAEAA==" My problem is to decompress the string "H4sIAAAAAAAEAA==" to "Hello world!". – LPCarlos Dec 20 '21 at 17:29
  • 1
    All you have there is a gzip header. So it is _not_ ok up to there. – Mark Adler Dec 21 '21 at 05:07

0 Answers0