Home > Article > Backend Development > Compress and decompress files using GZIP format in C#
To compress and decompress files using the GZIP format, use the GZipStream class.
To compress files, use the GZipStream class and the FileStream class. Set the following parameters.
The file to be compressed and the name of the output zip file.
Here, outputFile is the output file, which is read into FileStream.
p>
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); } }
To decompress a file, use the same GZipStream class. Set the following parameters: the names of the source and output files.
From the source zip file, open GZipStream.
using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))
To decompress, use a loop and read the data from the stream. Write it to the output stream and generate a file. This file is the file we decompressed.
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; } }
The above is the detailed content of Compress and decompress files using GZIP format in C#. For more information, please follow other related articles on the PHP Chinese website!