C# ZIP 壓縮解壓


ZIP流是在NetFramework4.5 引入的目的是為了能夠更好的操作ZIP文件,進行壓縮解壓等操作。與ZIP流相關的幾個類是:

  1. ZipArchive 代表一個ZIP的壓縮包文件
  2. ZipArchiveEntry 代表ZIP壓縮包中的一個文件
  3. ZipFile 提供了一系列的靜態方法來幫助用戶更方便地操作ZIP文件,類似於File類的作用。

注意:在使用之前請先添加程序集引用System.IO.CompressionSystem.IO.Compression.FileStream

 

/// <summary>
/// 測試
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnZIP_Click(object sender, EventArgs e)
{
ZIPYS();
ZIPJY();
}

/// <summary>
/// 創建壓縮zip文檔
/// </summary>
private void ZIPYS()
{
using (FileStream fs = new FileStream("Zip123.zip", FileMode.Create))
{
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create))
{
//創建文檔文件
ZipArchiveEntry entry = zipArchive.CreateEntry("HelloWorld.txt");
//文檔文件寫入內容
using (StreamWriter writer = new StreamWriter(entry.Open(), Encoding.Default))
{
writer.Write("I am 魯迅認識的那只猹! Hello World");
}
}
}
}

/// <summary>
/// 解壓zip文檔
/// </summary>
private void ZIPJY()
{
using (FileStream fs = new FileStream("log.zip", FileMode.Open))
{
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
{
//創建存放解壓文件目錄
Directory.CreateDirectory("log123");
//解壓所有文檔文件
foreach (var it in zipArchive.Entries)
{
it.ExtractToFile(@"log123\" + it.Name);
}
}
}
}

/// <summary>
/// 向zip文檔中添加文檔
/// </summary>
private void ZIPYStj()
{
using (FileStream fs = new FileStream("Zip123.zip", FileMode.Open))
{
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
{
ZipArchiveEntry entry = zipArchive.CreateEntry("AppendFile.txt");
using (StreamWriter wr = new StreamWriter(entry.Open(), Encoding.Default))
{
wr.Write("追加內容123!");
}
}
}
}

 

ZipFile

方法 解釋
FileZip.CreateFromDirectory 從一個目錄創建ZIP壓縮文件
FileZip.ExtractToDirectory 將ZIP壓縮文件解壓到目錄中
FileZip.Open 打開一個ZIP壓縮文件
FileZip.OpenRead 打開一個讀取模式的ZIP壓縮文件

ZipFileExtensions

ZipFileExtensions 為ZipArchive 和 ZipArchiveEntry 提供了一些更簡便的方法,具體可以查看官方文檔

原文鏈接:https://www.cnblogs.com/slyfox/p/11231375.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM