To compress and decompress using GZip in C# and VB.NET you can use the Following snippet.

Samples

Sample C#

public static byte[] DecompressGZip(byte[] bytesToDecompress)
{
	using (GZipStream stream = new GZipStream(new MemoryStream(bytesToDecompress), CompressionMode.Decompress))
	{
		const int size = 4096;
		byte[] buffer = new byte[size];
		using (MemoryStream memoryStream = new MemoryStream())
		{
			int count;
			do
			{
				count = stream.Read(buffer, 0, size);
				if (count > 0)
				{
					memoryStream.Write(buffer, 0, count);
				}
			} while (count > 0);
			return memoryStream.ToArray();
		}
	}
}

public static byte[] CompressGZip(string input, Encoding encoding = null)
{
	encoding = encoding ?? Encoding.Unicode;
	byte[] bytes = encoding.GetBytes(input);
	using (MemoryStream stream = new MemoryStream())
	{
		using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress))
		{
			zipStream.Write(bytes, 0, bytes.Length);
			return stream.ToArray();
		}
	}
}

Sample VB.NET

Public Function DecompressGZip(bytesToDecompress As Byte()) As Byte()
	Using stream As New GZipStream(New MemoryStream(bytesToDecompress), CompressionMode.Decompress)
		Const size As Integer = 4096
		Dim buffer As Byte() = New Byte(size - 1) {}
		Using memoryStream As New MemoryStream()
			Dim count As Integer
			Do
				count = stream.Read(buffer, 0, size)
				If count > 0 Then
					memoryStream.Write(buffer, 0, count)
				End If
			Loop While count > 0
			Return memoryStream.ToArray()
		End Using
	End Using
End Function

Public Function CompressGZip(input As String, Optional encoding As Encoding = Nothing) As Byte()
	encoding = If(encoding, Encoding.Unicode)
	Dim bytes As Byte() = encoding.GetBytes(input)
	Using stream As New MemoryStream()
		Using zipStream As New GZipStream(stream, CompressionMode.Compress)
			zipStream.Write(bytes, 0, bytes.Length)
			Return stream.ToArray()
		End Using
	End Using
End Function

 

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

 

5 thought on “How to compress and decompress using GZip in C# and VB.NET”

Leave a Reply