Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Nén và giải nén file dùng GZIP Format trong C#

Dùng class GZipStream để compress/decompress file GZIP.

Nén (Compress)

Dùng GZipStream với FileStream. Tham số: file nguồn, file zip đầu ra.

Ví dụ

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

Giải nén (Decompress)

Dùng GZipStream với CompressionMode.Decompress. Tham số: file zip nguồn, file đầu ra.

using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))

Đọc loop cho đến hết stream, write ra output stream.

Ví dụ

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