.Net Core 多檔案打包壓縮的實現程式碼
阿新 • • 發佈:2021-12-26
最近專案需要實現多檔案打包的功能,嘗試了一些方法,最後發現使用 ICSharpCode.SharpZipLib 最符合專案的要求。
具體實現如下:
1.在 Nuget 中安裝 ICSharpCode.SharpZipLib
2.將要打包的檔案放到同個資料夾進行壓縮:
①壓縮資料夾
/// <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"; //預設壓縮在桌面上 if (!Directory.Exists(Path.GetDirectoryName(dest))) //檔案不存在就根據路徑建立 E:\\test Directory.CreateDirectory(Path.GetDirectoryName(dest)); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(dest))) { zipStream.SetLevel(6); //壓縮級別0-9 CreateZip(dir,zipStream); fileName = dest; zipStream.Finish(); zipStream.Close(); } return true; } /// <summary> /// 壓縮內容到 zipStream 流中 /// </summary> /// <param name="source">原始檔</param> /// <param name="zipStream">目標檔案流(全路徑+檔名+.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 = ne客棧w byte[fs.Length]; fs.Read(buffer,buffer.Length); string tempFileName = file.Substring(file.LastIndexOf("\\") + 1); //獲得當前檔案路徑的檔名 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,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(savepwww.cppcns.comath);
if (!file.Directory.Exists)
{
file.Directory.Create();
}
}
Crc32 crc = new Crc32();
using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(savepath)))
{
zipStream.SetLevel(9); //壓縮級別0-9
foreach (var url in fileList)
{
byte[] buffer = new WebClient().DownloadData(url);
string tempFileName = GetFileNameByUrl(url); //獲得當前檔案路徑的檔名
ZipEntry entry = new ZipEntry(tempFileName);
entry.DateTime = DateTime.Now;
entry.Size = buffer.Length;
crc.Reset();
crc.Update(buffer);
zipStream.PutNextEntry(entry);
zipStream.Write(buffer,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); } }
通過此方法生成的壓縮包,所有檔案都會顯示在同一層。
③如果需要在檔案中建立目錄,需要在檔案SYOEYUfdKy名稱上指定檔案路徑
新增工具類:
/// <summary>
/// 檔案物件
/// </summary>
public class FileItem
{
/// <summary>
/// 檔名稱
/// &SYOEYUfdKylt;/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); //壓縮級別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,buffer.Length);
}
}
}
catch (Exception ex)
{
error = "檔案打包失敗:" + ex.Message;
}
return url;
}
呼叫引數示例:
{ "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" } ] }
生成的結果:
到此這篇關於.Net Core 多檔案打包壓縮的實現程式碼的文章就介紹到這了,更多相關.Net Core 多檔案打包壓縮內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!