首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 單檔案壓縮與解壓縮(GZipStream 基礎版)

     編輯:關於C語言

.NET Framework 2.0 引入 System.IO.Compression.GZipStream,提供基本壓縮/解壓功能。本文示範單一檔案的壓縮與還原。

壓縮方法

public static void Compress(string filePath, string zipPath) {
    using (FileStream source = File.OpenRead(filePath))
    using (FileStream dest = File.Create(zipPath))
    using (GZipStream zip = new GZipStream(dest, CompressionMode.Compress)) {
        byte[] buffer = new byte[source.Length];
        source.Read(buffer, 0, buffer.Length);
        zip.Write(buffer, 0, buffer.Length);
    }
}

解壓縮方法

public static void Decompress(string zipPath, string filePath) {
    using (FileStream source = File.OpenRead(zipPath))
    using (FileStream dest = File.Create(filePath))
    using (GZipStream unzip = new GZipStream(source, CompressionMode.Decompress)) {
        byte[] buffer = new byte[source.Length];
        int read = unzip.Read(buffer, 0, buffer.Length);
        dest.Write(buffer, 0, read);
    }
}

使用範例

string folder = Path.Combine(Server.MapPath("~"), "TestCompress");
Compress(Path.Combine(folder, "file1.txt"), Path.Combine(folder, "myzip"));
Decompress(Path.Combine(folder, "myzip"), Path.Combine(folder, "zipfolder", "file1.txt"));

注意:GZipStream 僅支援單一資料流壓縮,若需打包多檔案,請參考進階版(結合 Tar 或自訂格式)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved