Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compressing and Decompressing files in C#
Use the System.IO.Compression Namespace in C# to compress and decompress files in C#.
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. Seth 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;
}
}Advertisements