Working with GZip Archives

Overview

Aspose.ZIP for .NET API lets work with creating and managing GZip archives in your applications without the need of any other 3rd party applications. Aspose.ZIP API provides  GZipArchive class to work with GZip archives. This class provides various methods to perform operations on archives.

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 shows how to compress a file using GZipArchive instance.

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 shows how to open a GZip archive.

 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 shows how to open an archive from a stream and extract it 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        Console.WriteLine(archive.Name);
7    }

Save to Stream

The following code example shows how to open and save to 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    }
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.