
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Compressing and Decompressing files using GZIP Format in C#
To compress and decompress files using GZIP Format, use the GZipStream class.
Compress
To zip a file, use the GZipStream class with the FileStream class. Set the following parameters.
File to be zipped and the name of the output zip file.
Here, outputFile is the output file and the file is read into the FileStream.
Example
using(var compress = new GZipStream(outputFile, CompressionMode.Compress, false)) { byte[] b = new byte[inFile.Length]; int read = inFile.Read(b, 0, b.Length); while (read > 0) { compress.Write(b, 0, read); read = inFile.Read(b, 0, b.Length); } }
Decompress
To decompress a file, use the same the GZipStream class. Set the following parameters: source file and the name of the output file.
From the source zip file, open a GZipStream.
using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))
To decompress, use a loop and read as long as you have data in the stream. Write it to the output stream and a file generates. The file is our decompressed file.
Example
using(var zip = new GZipStream(inputStream, CompressionMode.Decompress, true)) { byte[] b = new byte[inputStream.Length]; while (true) { int count = zip.Read(b, 0, b.Length); if (count != 0) outputStream.Write(b, 0, count); if (count != b.Length) break; } }
- Related Articles
- Compressing and Decompressing files in C#
- Python Support for gzip files (gzip)
- Decompressing Files in Linux with Gunzip
- Using gzip and gunzip in Linux
- Listing out directories and files using C#
- Compressing string in JavaScript
- Compressing a File in Golang
- How can I extract or uncompress gzip file using php?
- Date format validation using C# Regex
- Print “Hello World” in C/C++ without using header files
- What is the common header format of Python files?
- What are the text files and binary files in C language?
- Compression compatible with gzip in Python (zlib)
- How To enable GZIP Compression in PHP?
- Listing modified, old and newly created files on Linux using C++

Advertisements