The .NET Framework provides many compression types in System.IO.Compression
. In VB.NET the GZipStream
type is used to compress data.
We use VB.NET code to compress a string
to a file. After compressing the data, we test to ensure the code correctly works.
First, we generate a string
and convert it to a byte
array. We use the GetBytes
method in System.Text
to do this conversion.
byte
array to our custom Compress function. In Compress, we use several streams.MemoryStream
as a buffer for the GZipStream
. When write to the GZipStream
, we actually write to the buffer.Compress()
performs the compression logic. We must use CompressionMode.Compress
to implement compression.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.
string
had 10,000 characters. And, when converted to an ASCII string
, this comes out to 10,000 bytes.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
, can be used. We can convert any data type to a byte
array.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.