C#?使用原生?System.IO.Compression?實(shí)現(xiàn)?zip?的壓縮與解壓
zip 是一個(gè)非常常見的壓縮包格式,本文主要用于說明如何使用代碼 文件或文件夾壓縮為 zip壓縮包及其解壓操作,
我們采用的是 微軟官方的實(shí)現(xiàn),所以也不需要安裝第三方的組件包。
使用的時(shí)候記得 using System.IO.Compression;
/// <summary>
/// 將指定目錄壓縮為Zip文件
/// </summary>
/// <param name="folderPath">文件夾地址 D:/1/ </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
public static void CompressDirectoryZip(string folderPath, string zipPath)
{
DirectoryInfo directoryInfo = new(zipPath);
if (directoryInfo.Parent != null)
{
directoryInfo = directoryInfo.Parent;
}
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
ZipFile.CreateFromDirectory(folderPath, zipPath, CompressionLevel.Optimal, false);
}其中 CompressionLevel 是個(gè)枚舉,支持下面四種類型
| 枚舉 | 值 | 注解 |
|---|---|---|
| Optimal | 0 | 壓縮操作應(yīng)以最佳方式平衡壓縮速度和輸出大小。 |
| Fastest | 1 | 即使結(jié)果文件未可選擇性地壓縮,壓縮操作也應(yīng)盡快完成。 |
| NoCompression | 2 | 該文件不應(yīng)執(zhí)行壓縮。 |
| SmallestSize | 3 | 壓縮操作應(yīng)盡可能小地創(chuàng)建輸出,即使該操作需要更長的時(shí)間才能完成。 |
我方法這里直接固定了采用 CompressionLevel.Optimal,大家可以根據(jù)個(gè)人需求自行調(diào)整。
/// <summary>
/// 將指定文件壓縮為Zip文件
/// </summary>
/// <param name="filePath">文件地址 D:/1.txt </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
public static void CompressFileZip(string filePath, string zipPath)
{
FileInfo fileInfo = new FileInfo(filePath);
string dirPath = fileInfo.DirectoryName?.Replace("\\", "/") + "/";
string tempPath = dirPath + Guid.NewGuid() + "_temp/";
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
fileInfo.CopyTo(tempPath + fileInfo.Name);
CompressDirectoryZip(tempPath, zipPath);
DirectoryInfo directory = new(path);
if (directory.Exists)
{
//將文件夾屬性設(shè)置為普通,如:只讀文件夾設(shè)置為普通
directory.Attributes = FileAttributes.Normal;
directory.Delete(true);
}
}
壓縮單個(gè)文件的邏輯其實(shí)就是先將我們要壓縮的文件復(fù)制到一個(gè)臨時(shí)目錄,然后對臨時(shí)目錄執(zhí)行了壓縮動作,壓縮完成之后又刪除了臨時(shí)目錄。
/// <summary>
/// 解壓Zip文件到指定目錄
/// </summary>
/// <param name="zipPath">zip地址 D:/1.zip</param>
/// <param name="folderPath">文件夾地址 D:/1/</param>
public static void DecompressZip(string zipPath, string folderPath)
{
DirectoryInfo directoryInfo = new(folderPath);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
ZipFile.ExtractToDirectory(zipPath, folderPath);
}
至此 C# 使用原生 System.IO.Compression 實(shí)現(xiàn) zip 的壓縮與解壓 就講解完了,有任何不明白的,可以在文章下面評論或者私信我,歡迎大家積極的討論交流,有興趣的朋友可以關(guān)注我目前在維護(hù)的一個(gè) .NET 基礎(chǔ)框架項(xiàng)目,項(xiàng)目地址如下
https://github.com/berkerdong/NetEngine.git
https://gitee.com/berkerdong/NetEngine.git
到此這篇關(guān)于C# 使用原生 System.IO.Compression 實(shí)現(xiàn) zip 的壓縮與解壓的文章就介紹到這了,更多相關(guān)C# 實(shí)現(xiàn) zip 的壓縮與解壓內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)關(guān)閉其他程序窗口或進(jìn)程代碼分享
這篇文章主要介紹了C#實(shí)現(xiàn)關(guān)閉其他程序窗口或進(jìn)程代碼分享,本文給出了兩種方法,并分別給出示例代碼,需要的朋友可以參考下2015-06-06
C#實(shí)現(xiàn)文件篩選讀取并翻譯的自動化工具
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)文件篩選及讀取內(nèi)容,并翻譯的自動化工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-03-03

