C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Also: Any Byte array, not just an ASCII-encoded string, can be used. We can convert any data type to a byte array.