Compress and decompress files using GZIP format in C#

WBOY
Release: 2023-09-01 14:53:07
forward
928 people have browsed it

在 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); } }
Copy after login

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))
Copy after login

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; } }
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!