Home  >  Article  >  Backend Development  >  Compress and decompress files using GZIP format in C#

Compress and decompress files using GZIP format in C#

WBOY
WBOYforward
2023-09-01 14:53:071023browse

在 C# 中使用 GZIP 格式压缩和解压缩文件

To compress and decompress files using the GZIP format, use the GZipStream class.

Compression

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>

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);
   }
}

Decompression

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.

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;
   }
}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete