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 (.gz) programmatically in C#. Moreover, the article will also cover how to decompress GZip archives in C#.
- .NET API to Compress and Decompress Files using GZip
- Compress Files using GZip in C#
- Decompress a GZip Archive in C#
- Extract a GZip Archive into Stream in C#
C# API to Compress and Decompress Files using GZip
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
Compress Files using GZip in C#
The following are the steps to compress files using 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 Archive in C#
The following are the steps to decompress a GZip archive in C# using Aspose.ZIP for .NET.
- 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 using C#.
Extact a GZip Archive 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 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#.
Get a Free API License
You can get a free temporary license in order to use the API without evaluation limitations.
Conclusion
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. You can explore more about Aspose.ZIP for .NET using documentation. In addition, you can contact us to share your queries via our forum.