C# ZipArchive加壓解壓zip文件方式
更新時間:2025年11月06日 14:11:58 作者:mouka~
本文介紹了一種在內(nèi)存中創(chuàng)建zip文件并獲取其流的方法,從而避免了創(chuàng)建臨時文件和下載文件的需要,最后展示了如何解壓該zip文件
創(chuàng)建zip文件
using (var fileStream = new FileStream(saveZipName, FileMode.CreateNew))
{
// 使用內(nèi)存流創(chuàng)建壓縮文件
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
{
var files = Directory.GetFiles(taskDir, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
//相對路徑
var relativePath = Path.GetRelativePath(FileAndFolderConfig.CollectionSpaceFolder.Path, file);
archive.CreateEntryFromFile(file, relativePath);
}
}
}獲取zip文件流,在內(nèi)存中創(chuàng)建zip文件避免創(chuàng)建臨時文件
using (var memoryStream = new MemoryStream())
{
// 使用內(nèi)存流創(chuàng)建壓縮文件
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var files = Directory.GetFiles(taskDir, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
//相對路徑
var relativePath = Path.GetRelativePath(FileAndFolderConfig.CollectionSpaceFolder.Path, file);
var entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
using var entryStream = entry.Open();
using var fileStream = File.OpenRead(file);
await fileStream.CopyToAsync(entryStream);
}
}
memoryStream.Position = 0; // 重置流位置
}下載文件并解壓
// 下載文件到內(nèi)存流
using (var memoryStream = new MemoryStream())
{
await taskFile.CopyToAsync(memoryStream);
taskFile.Close();
memoryStream.Position = 0; // 重置流位置
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
var entryOutputPath = Path.Combine(FileAndFolderConfig.CollectionSpaceFolder.Path, entry.FullName);
// 如果是目錄條目,創(chuàng)建目錄
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath));
continue;
}
// 確保父目錄存在
var parentDir = Path.GetDirectoryName(entryOutputPath);
if (!string.IsNullOrEmpty(parentDir))
{
Directory.CreateDirectory(parentDir);
}
// 解壓文件
entry.ExtractToFile(entryOutputPath, overwrite: true);
}
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#利用System.Threading.Thread.Sleep即時輸出信息的詳解
本篇文章是對C#利用System.Threading.Thread.Sleep即時輸出信息進行了詳細的分析介紹,需要的朋友參考下2013-06-06
C# 中類型轉(zhuǎn)換方式之顯式轉(zhuǎn)換和 as 運算符
在 C# 中,有兩種常見的類型轉(zhuǎn)換方式:顯式轉(zhuǎn)換和as 運算符,它們用于在不同類型之間進行轉(zhuǎn)換,以下是對這兩種轉(zhuǎn)換方式的詳細解釋和示例說明,感興趣的朋友跟隨小編一起看看吧
2024-05-05
insert語句太長用StringBuilder優(yōu)化一下
insert語句太長用StringBuilder優(yōu)化一下,下面是示例代碼,需要的朋友可以研究研究
2014-07-07 
