Detail We use MemoryStream as a buffer for the GZipStream. When write to the GZipStream, we actually write to the buffer.
Info Compress() performs the compression logic. We must use CompressionMode.Compress to implement compression.
Important Both the MemoryStream and the GZipStream are wrapped in Using-statements. These do correct cleanup of memory and system resources.
Imports System.IO
Imports System.IO.Compression
Imports System.Text
Module Module1
Sub Main()
' Byte array from string.
Dim array() As Byte = Encoding.ASCII.GetBytes(New String("X"c, 10000))
' Call Compress.
Dim c() As Byte = Compress(array)
' Write bytes.
File.WriteAllBytes("C:\\compress.gz", c)
End Sub
''' <summary>
''' Receives bytes, returns compressed bytes.
''' </summary>
Function Compress(ByVal raw() As Byte) As Byte()
' Clean up memory with Using-statements.
Using memory As MemoryStream = New MemoryStream()
' Create compression stream.
Using gzip As GZipStream = New GZipStream(memory, CompressionMode.Compress, True)
' Write.
gzip.Write(raw, 0, raw.Length)
End Using
' Return array.
Return memory.ToArray()
End Using
End Function
End Module
To test this code, I executed the finished program. The file (compress.gz) required 213 bytes on the disk. I expanded the file with 7-Zip. And the resulting file (compress) required 10,000 bytes.
And The original string had 10,000 characters. And, when converted to an ASCII string, this comes out to 10,000 bytes.
Discussion. Instead of using a New String, created with the String constructor, you could read in a file. Try the File.ReadAllText method to get the original string.
Also Any Byte array, not just an ASCII-encoded string, can be used. We can convert any data type to a byte array.
A summary. Compression trades time for space. It adds an additional computational step, but reduces disk space. We saw how to compress any byte array with GZipStream in the VB.NET language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 19, 2023 (edit).