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.
' 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.
''' Receives bytes, returns compressed bytes.
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)
gzip.Write(raw, 0, raw.Length)
' Return array.
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.