Home
Search
VB.NET Compress File (GZipStream)Compress a string to a GZIP file with the GZipStream Class.
Compress. The .NET Framework provides many compression types in System.IO.Compression. In VB.NET the GZipStream type is used to compress data.
Compression functions. We use VB.NET code to compress a string to a file. After compressing the data, 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.
And 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
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.
String Constructor
File.ReadAllText
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.
Home
© 2007-2022 sam allen.
see site info on the changelog.