C#實(shí)現(xiàn)多文件打包壓縮(.Net?Core)
最近項(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)建目錄,需要在文件名稱上指定文件路徑
添加工具類:
/// <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é)果:
以上所述是小編給大家介紹的.Net Core框架下C#實(shí)現(xiàn)多文件打包壓縮的方法,希望對(duì)大家有所幫助。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
C#Js時(shí)間格式化問(wèn)題簡(jiǎn)單實(shí)例
這篇文章介紹了C#Js時(shí)間格式化問(wèn)題簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-10-10C#使用BinaryFormatter類、ISerializable接口、XmlSerializer類進(jìn)行序列化和反序列
這篇文章介紹了C#使用BinaryFormatter類、ISerializable接口、XmlSerializer類進(jìn)行序列化和反序列化的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-0910個(gè)C#程序員經(jīng)常用到的實(shí)用代碼片段
如果你是一個(gè)C#程序員,那么本文介紹的10個(gè)C#常用代碼片段一定會(huì)給你帶來(lái)幫助,從底層的資源操作,到上層的UI應(yīng)用,這些代碼也許能給你的開(kāi)發(fā)節(jié)省不少時(shí)間。以下是原文:2015-09-09Unity?UGUI的PhysicsRaycaster物理射線檢測(cè)組件介紹使用
這篇文章主要介紹了Unity?UGUI的PhysicsRaycaster物理射線檢測(cè)組件的介紹及使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07C#實(shí)現(xiàn)Excel轉(zhuǎn)PDF時(shí)設(shè)置內(nèi)容適應(yīng)頁(yè)面寬度
將Excel轉(zhuǎn)為PDF格式時(shí),通常情況下轉(zhuǎn)換出來(lái)的PDF頁(yè)面都是默認(rèn)的寬度大小。所以本文提供了C#實(shí)現(xiàn)Excel轉(zhuǎn)PDF時(shí)設(shè)置內(nèi)容適應(yīng)頁(yè)面寬度的示例代碼,需要的可以參考一下2022-04-04淺談Async和Await如何簡(jiǎn)化異步編程(幾個(gè)實(shí)例讓你徹底明白)
本篇文章主要介紹了淺談Async和Await如何簡(jiǎn)化異步編程,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-12-12