This page looks best with JavaScript enabled

VB.NET - Zip and Unzip String using GZipStream

 ·   ·  ☕ 2 min read

Original code that I found is in C#. So I converted it to VB.NET and confirmed working:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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).


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)