Working with Gzip Archives
Overview
Aspose.ZIP for .NET API allows you to create and manage GZip archives in your applications without relying on third-party software. The Aspose.ZIP API provides the GzipArchive class for working with GZip archives, offering various methods to perform operations on these archives.
The gzip compression algorithm is based on the DEFLATE algorithm, which is a combination of LZ77 and Huffman coding.
Compress a File
The following code example demonstrates how to compress a file using the GzipArchive class:
1 using (GzipArchive archive = new GzipArchive())
2 {
3 archive.SetSource(dataDir + "data.bin");
4 archive.Save(dataDir + "archive.gz");
5 }Open GZIP Archive
The following code example demonstrates how to open a GZip archive and extract its contents to a file stream:
1 //Extracts the archive and copies extracted content to file stream.
2 using (var archive = new GzipArchive(dataDir + "archive.gz"))
3 {
4 using (var extracted = File.Create(dataDir + "data.bin"))
5 {
6 var unpacked = archive.Open();
7 byte[] b = new byte[8192];
8 int bytesRead;
9 while (0 < (bytesRead = unpacked.Read(b, 0, b.Length)))
10 extracted.Write(b, 0, bytesRead);
11 }
12 }Extract to Memory Stream
The following code example demonstrates how to open a GZip archive from a stream and extract its contents to a MemoryStream:
1 //Open an archive from a stream and extract it to a MemoryStream
2 var ms = new MemoryStream();
3 using (GzipArchive archive = new GzipArchive(File.OpenRead(dataDir + "sample.gz")))
4 {
5 archive.Open().CopyTo(ms);
6 }Save to Stream
The following code example demonstrates how to open an archive and save it to a stream:
1 //Writes compressed data to http response stream.
2 var ms = new MemoryStream();
3 using (var archive = new GzipArchive())
4 {
5 archive.SetSource(new FileInfo(dataDir + "data.bin"));
6 archive.Save(ms);
7 }