使用 C# GZIP 格式壓縮和解壓縮檔案
要使用 GZIP 格式壓縮和解壓縮檔案,請使用 GZipStream 類。
壓縮
若要生成一個檔案的 zip,請將 GZipStream 類與 FileStream 類搭配使用。設定以下引數。
要生成 zip 的檔案和輸出 zip 檔案的名稱。
在此處,outputFile 是輸出檔案,檔案被讀取到 FileStream 中。
示例
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);
}
}解壓縮
若要解壓縮一個檔案,請使用同一個 GZipStream 類。設定以下引數:原始檔和輸出檔名稱。
從源 zip 檔案中開啟一個 GZipStream。
using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))
若要解壓縮,請使用一個迴圈並一直讀取流中的資料。將其寫入輸出流,並生成一個檔案。該檔案即為我們的已解壓縮檔案。
示例
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;
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP