This post shows how to compress a String to reduce the amount memory it consumes, and this post shows how to use the CompressText function. To be able to read the content of the string, it must be decompressed (or inflated) again. The DecompressText function is one way to do this.
Private Function DecompressText(ByVal B() As Byte) As String
Dim Result As New System.Text.StringBuilder()
Using MemStream As New System.IO.MemoryStream(B)
Using GZStream As New System.IO.Compression.GZipStream(MemStream, _
IO.Compression.CompressionMode.Decompress)
Do
'Note that this makes 1024 bytes in VB.
Dim Buffer(1023) As Byte
Dim BytesRead As Integer = GZStream.Read(Buffer, 0, 1024)
If BytesRead > 0 Then
Result.Append( _
System.Text.Encoding.UTF8.GetString(Buffer, 0, BytesRead))
End If
If BytesRead < 1024 Then
Exit Do
End If
Loop
GZStream.Close()
Return Result.ToString()
End Using
End Using
End Function
Now, imagine that B is a byte array returned from the CompressText function. B holds the bytes of a compressed text string. B is passed to the DecompressText function and the function returns the inflated string again. Example:
'Create some text. Dim S As String = "This is some text that I want to compress. Preferably it's " & _ "a long string loaded from a text file or some XML document." 'Assign the compressed version to the variable B. Dim B() As Byte = CompressText(S.ToString()) 'Decompress it, and display the result. Dim Decompressed As String = DecompressText(B) Console.WriteLine(Decompressed)
Have you seen a more elegant way to handle strings in memory than what the .NET Framework offers?
Leave a Reply