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