HomeSearch

VB.NET Compress File: GZipStream Example

Compress a string to a GZIP file with the GZipStream Class.
Compress. The .NET Framework provides compression in System.IO.Compression. The GZipStream is used to compress data. We use VB.NET code to compress a string to a file. We test to ensure the code correctly works.File
Example. First, we generate a string and convert it to a byte array. We use the GetBytes method in System.Text to do this conversion. We pass this byte array to our custom Compress function. In Compress, we use several streams.Byte Array

MemoryStream: We use MemoryStream as a buffer for the GZipStream. When write to the GZipStream, we actually write to the buffer.

GZipStream: This performs the compression logic. We must use CompressionMode.Compress to implement compression.

Using: Both the MemoryStream and the GZipStream are wrapped in Using-statements. These do correct cleanup of memory and system resources.

VB.NET program that compresses string to file 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.7-Zip Command-Line
The original string had 10,000 characters. And, when converted to an ASCII string where each character is one byte, this comes out to 10,000 bytes. Because each character was the same, it compressed to a small size.
Discussion. This code can be changed to suit your needs. 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.String ConstructorFile.ReadAllText

Also: Any Byte array, not just an ASCII-encoded string, can be used. We can convert any data type to a byte array.

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. The example can be changed to fit other needs.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.