GZip archives (.gz) are used to compress one or more files using the GNU zip compression algorithm. It is commonly used for file compression in UNIX operating systems. In this article, you will learn how to compress files using GZip in C#. Moreover, the article will also cover how to decompress GZip archives in C#.
- C# GZip API to Compress and Decompress Files
- Compress Files using GZip in C#
- Decompress a GZip Archive in C#
- Extract a GZip Archive into Stream in C#
Compress Files with GZip in C# - API Installation
To compress and decompress files using GZip, we will use Aspose.ZIP for .NET. It is a powerful API that lets you work with popular archive formats including ZIP, 7z, GZip, etc. You can either download the API or install it using NuGet.
PM> Install-Package Aspose.Zip
GZip File Compression in C#
The following are the steps to compress files with GZip in C#.
- Create an object of the GzipArchive class.
- Use GzipArchive.SetSource(String) method to add a file to archive.
- Create GZip archive using GzipArchive.Save(String) method.
The following code sample shows how to compress files to GZip in C#.
Decompress a GZip in C#
The following are the steps to decompress a GZip archive in C#.
- Create an object of the GzipArchive class and initialize it with GZip archive’s path.
- Create a file for extracted content using File.Create(String) method.
- Open GZip for extraction using GZipArchive.Open() method.
- Read the extracted content and write it to the file.
The following code sample shows how to decompress a GZip archive in C#.
Extract a GZip into Stream in C#
You can also extract a GZip archive into a memory stream object. The following are the steps to perform this operation.
- Create a new MemoryStream object.
- Create an object of GzipArchive class and initialize it with GZip archive’s path.
- Extract GZip and copy to the memory stream using GZipArchive.Open().CopyTo(MemoryStream) method.
The following code sample shows how to extract a GZip archive into a memory stream using C#.
Compress and Decompress GZip Files - Get a Free License
You can get a free temporary license to compress or decompress GZip archives without evaluation limitations.
In this article, you have learned how to compress or decompress files using GZip in C#. Furthermore, you have seen how to extract a GZip to stream programmatically using C# .NET. You can explore more about Aspose.ZIP for .NET using documentation. In addition, you can contact us to share your queries via our forum.