.Net Core 多文件打包壓縮的實(shí)現(xiàn)代碼
最近項(xiàng)目需要實(shí)現(xiàn)多文件打包的功能,嘗試了一些方法,最后發(fā)現(xiàn)使用? ICSharpCode.SharpZipLib 最符合項(xiàng)目的要求。
具體實(shí)現(xiàn)如下:
1.在 Nuget 中安裝? ICSharpCode.SharpZipLib

2.將要打包的文件放到同個(gè)文件夾進(jìn)行壓縮:
①壓縮文件夾
/// <summary>
/// 壓縮文件
/// </summary>
/// <param name="fileName">壓縮后獲得的文件名</param>
public static bool CompressFile(string dir, out string fileName)
{
string dest = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\" + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".zip"; //默認(rèn)壓縮在桌面上
if (!Directory.Exists(Path.GetDirectoryName(dest))) //文件不存在就根據(jù)路徑創(chuàng)建 E:\\test
Directory.CreateDirectory(Path.GetDirectoryName(dest));
using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(dest)))
{
zipStream.SetLevel(6); //壓縮級(jí)別0-9
CreateZip(dir, zipStream);
fileName = dest;
zipStream.Finish();
zipStream.Close();
}
return true;
}
/// <summary>
/// 壓縮內(nèi)容到 zipStream 流中
/// </summary>
/// <param name="source">源文件</param>
/// <param name="zipStream">目標(biāo)文件流(全路徑+文件名+.zip)</param>
private static void CreateZip(string source, ZipOutputStream zipStream)
{
Crc32 crc = new Crc32();
string[] files = Directory.GetFileSystemEntries(source); //獲得所有文件名稱和目錄名稱
foreach (var file in files)
{
if (Directory.Exists(file)) //如果是文件夾里有文件則遞歸
{
CreateZip(file, zipStream);
}
else //如果不是則壓縮
{
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string tempFileName = file.Substring(file.LastIndexOf("\\") + 1); //獲得當(dāng)前文件路徑的文件名
ZipEntry entry = new ZipEntry(tempFileName);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
}
}
②將指定文件打包壓縮 (可打包線上文件)
/// <summary>
/// 打包線上線下文件
/// </summary>
/// <param name="fileList">文件列表</param>
/// <param name="savepath">保存路徑</param>
public static void ZipOnlineFile3(List<string> fileList, string savepath)
{
//判斷保存的文件目錄是否存在
if (!File.Exists(savepath))
{
var file = new FileInfo(savepath);
if (!file.Directory.Exists)
{
file.Directory.Create();
}
}
Crc32 crc = new Crc32();
using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(savepath)))
{
zipStream.SetLevel(9); //壓縮級(jí)別0-9
foreach (var url in fileList)
{
byte[] buffer = new WebClient().DownloadData(url);
string tempFileName = GetFileNameByUrl(url); //獲得當(dāng)前文件路徑的文件名
ZipEntry entry = new ZipEntry(tempFileName);
entry.DateTime = DateTime.Now;
entry.Size = buffer.Length;
crc.Reset();
crc.Update(buffer);
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
}
從文件路徑讀取文件名的方法:
public static string GetFileNameByUrl(string url)
{
//判斷路徑是否為空
if (string.IsNullOrWhiteSpace(url)) return null;
//判斷是否為線上文件
if (url.ToLower().StartsWith("http"))
{
return url.Substring(url.LastIndexOf("/") + 1);
}
else
{
return url.Substring(url.LastIndexOf("\\") + 1);
}
}
通過(guò)此方法生成的壓縮包,所有文件都會(huì)顯示在同一層。
③如果需要在文件中創(chuàng)建目錄,需要在文件名稱上指定文件路徑
添加工具類(lèi):
/// <summary>
/// 文件對(duì)象
/// </summary>
public class FileItem
{
/// <summary>
/// 文件名稱
/// </summary>
public string FileName { get; set; }
/// <summary>
/// 文件路徑
/// </summary>
public string FileUrl { get; set; }
}
壓縮文件的方法:
/// <summary>
/// 打包線上線下文件
/// </summary>
/// <param name="zipName">壓縮文件名稱</param>
/// <param name="fileList">文件列表</param>
/// <param name="savepath">保存路徑</param>
public static string ZipFiles(string zipName, List<FileItem> fileList, out string error)
{
error = string.Empty;
string path = string.Format("/files/zipFiles/{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
//文件保存目錄
string directory = FileSavePath + path;
string url = FileHostUrl.TrimEnd('/') + path + zipName;
string savePath = directory + zipName;
try
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(savePath)))
{
zipStream.SetLevel(9); //壓縮級(jí)別0-9
foreach (var item in fileList)
{
byte[] buffer = new WebClient().DownloadData(item.FileUrl);
ZipEntry entry = new ZipEntry(item.FileName);
entry.DateTime = DateTime.Now;
entry.Size = buffer.Length;
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
error = "文件打包失?。? + ex.Message;
}
return url;
}
調(diào)用參數(shù)示例:
{
"zipName": "test.zip",
"fileList": [
{
"fileName": "123.png",
"fileUrl": "https://file.yidongcha.cn/files/uploadfiles/image/2021/11/15/11c6de395fcc484faf4745ade62cf6e6.png"
},
{
"fileName": "123/456/789.jpg",
"fileUrl": "https://file.yidongcha.cn/files/uploadfiles/image/2021/11/15/fe922b250acf4344b8ca4d2aad6e0355.jpg"
}
]
}
生成的結(jié)果:

到此這篇關(guān)于.Net Core 多文件打包壓縮的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān).Net Core 多文件打包壓縮內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
.NET中如何將文本文件的內(nèi)容存儲(chǔ)到DataSet
大家在項(xiàng)目中比較多的會(huì)對(duì)文件進(jìn)行操作,例如文件的上傳下載,文件的壓縮和解壓等IO操作。而在.NET項(xiàng)目中較多的會(huì)使用DataSet,DataTable進(jìn)行數(shù)據(jù)的緩存。每一個(gè)DataSet都是一個(gè)或多個(gè)DataTable對(duì)象的集合,本文主要介紹的是如何將文本文件的內(nèi)容存儲(chǔ)到DataSet里去。2016-12-12
asp.net 圖片的讀寫(xiě)入庫(kù)實(shí)現(xiàn)代碼
asp.net對(duì)圖片的讀寫(xiě),實(shí)現(xiàn)將圖片保存到數(shù)據(jù)庫(kù)中,然后再讀取顯示的實(shí)現(xiàn)代碼。2009-11-11
Asp.Net 網(wǎng)站優(yōu)化系列之?dāng)?shù)據(jù)庫(kù)優(yōu)化措施 使用主從庫(kù)(全)
網(wǎng)站規(guī)模到了一定程度之后,該分的也分了,該優(yōu)化的也做了優(yōu)化,但是還是不能滿足業(yè)務(wù)上對(duì)性能的要求;這時(shí)候我們可以考慮使用主從庫(kù)。2010-06-06
ASP.NET基于Ajax的Enter鍵提交問(wèn)題分析
這篇文章主要介紹了ASP.NET基于Ajax的Enter鍵提交,結(jié)合實(shí)例形式分析了asp.net基于ajax響應(yīng)Enter鍵的提交方法與相關(guān)問(wèn)題解決技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
ASP.NET Core+Docker+Jenkins實(shí)現(xiàn)持續(xù)集成的完整實(shí)例
這篇文章主要給大家介紹了關(guān)于ASP.NET Core+Docker+Jenkins實(shí)現(xiàn)持續(xù)集成的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05
WPF實(shí)現(xiàn)定時(shí)刷新UI界面功能
這篇文章主要為大家詳細(xì)介紹了WPF實(shí)現(xiàn)定時(shí)刷新UI界面功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
MVC4制作網(wǎng)站教程第二章 用戶注冊(cè)2.1
這篇文章主要為大家詳細(xì)介紹了MVC4制作網(wǎng)站教程,用戶注冊(cè)功能的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08

