Tech Blog‎ > ‎

VB.NET - Zip and Unzip String using GZipStream

posted Nov 26, 2012, 1:22 PM by Victor Zakharov
Original code that I found is in C#. So I converted it to VB.NET and confirmed working:

Imports System.IO  
Public Shared Function Zip(text As String) As String
  Dim buffer As Byte() = System.Text.Encoding.Unicode.GetBytes(text)
  Dim ms As New MemoryStream()
  Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, True)
    zipStream.Write(buffer, 0, buffer.Length)
  End Using

  ms.Position = 0
  Dim outStream As New MemoryStream()

  Dim compressed As Byte() = New Byte(ms.Length - 1) {}
  ms.Read(compressed, 0, compressed.Length)

  Dim gzBuffer As Byte() = New Byte(compressed.Length + 3) {}
  System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length)
  System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4)
  Return Convert.ToBase64String(gzBuffer)
End Function

Public Shared Function UnZip(compressedText As String) As String
  Dim gzBuffer As Byte() = Convert.FromBase64String(compressedText)
  Using ms As New MemoryStream()
    Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
    ms.Write(gzBuffer, 4, gzBuffer.Length - 4)

    Dim buffer As Byte() = New Byte(msgLength - 1) {}

    ms.Position = 0
    Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
      zipStream.Read(buffer, 0, buffer.Length)
    End Using

    Return System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length)
  End Using
End Function

I tested this on HTML pages and it appears to be not the most efficient. In one of the examples, ~140K down to 44K.
In comparison, Total Commander can zip down to 27K at the average compression level. But even with minimal compression the file remains at 32K.
The best RAR can do is around 25K and 7-Zip can go as low as 24K. So I am in the process of finding something similar for .NET (hopefully such thing exists).