.Net Core 多文件打包壓縮的實現(xiàn)代碼
最近項目需要實現(xiàn)多文件打包的功能,嘗試了一些方法,最后發(fā)現(xiàn)使用? ICSharpCode.SharpZipLib 最符合項目的要求。
具體實現(xiàn)如下:
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))) //文件不存在就根據(jù)路徑創(chuàng)建 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>
/// 壓縮內(nèi)容到 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 = new byte[fs.Length];
fs.Read(buffer, 0, 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, 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); //壓縮級別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, 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);
}
}
通過此方法生成的壓縮包,所有文件都會顯示在同一層。
③如果需要在文件中創(chuàng)建目錄,需要在文件名稱上指定文件路徑
添加工具類:
/// <summary>
/// 文件對象
/// </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); //壓縮級別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"
}
]
}
生成的結果:

到此這篇關于.Net Core 多文件打包壓縮的實現(xiàn)代碼的文章就介紹到這了,更多相關.Net Core 多文件打包壓縮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
建立自定義的數(shù)據(jù)驅(qū)動的本地化資源provider
本文探討了自定義的本地化資源提供者.如果想用一個可替代系統(tǒng)的資源處理方案,例如把所有的資源放入數(shù)據(jù)庫中,而不是放在分散的資源文件里,你可以自定義一個resource provider.2010-06-06
asp.net 使用Silverlight操作ASPNETDB數(shù)據(jù)庫
asp.net下使用Silverlight操作ASPNETDB數(shù)據(jù)庫的實現(xiàn)代碼2010-01-01
Request.QueryString與一般NameValueCollection的區(qū)別
最近在做一個搜索程序的優(yōu)化改進,將搜索結果按照查詢的參數(shù)不同進行緩存。緩存的Key很自然的就想到了用查詢字符串,而獲取查詢字符串的最簡單方式是通過Request.QueryString.ToString()方法2011-12-12
asp.net中通過DropDownList的值去控制TextBox是否可編寫的實現(xiàn)代碼
Web窗體上有兩控件,DropDownList1,TextBox1,當DropDownList的值選擇是YES的時候,TextBox1可編輯,當選擇NO的時候,TextBox1的值為空,并且不能編輯,該如何實現(xiàn)2012-11-11
.NET Core 2.0 Preview2 發(fā)布匯總
這篇文章主要為大家詳細介紹了.NET Core 2.0 Preview2 發(fā)布匯總的相關內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
WEB上調(diào)用HttpWebRequest奇怪問題的解決方法
WEB上調(diào)用HttpWebRequest奇怪問題的解決方法...2007-04-04

