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

2.將要打包的文件放到同個文件夾進(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); //壓縮級別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); //壓縮級別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);
}
}
通過此方法生成的壓縮包,所有文件都會顯示在同一層。
③如果需要在文件中創(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"
}
]
}
生成的結(jié)果:

以上所述是小編給大家介紹的.Net Core框架下C#實現(xiàn)多文件打包壓縮的方法,希望對大家有所幫助。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
基于C#的socket編程的TCP異步的實現(xiàn)代碼
本篇文章主要介紹了基于C#的socket編程的TCP異步的實現(xiàn)代碼,詳解的講訴了TCP通信異步的實現(xiàn),有興趣的可以了解一下。2016-11-11
C# networkcomms 3.0實現(xiàn)模擬登陸總結(jié)
這篇文章主要介紹了C# networkcomms 3.0實現(xiàn)模擬登陸總結(jié),需要的朋友可以參考下2017-06-06
Unity UGUI實現(xiàn)滑動翻頁直接跳轉(zhuǎn)頁數(shù)
這篇文章主要為大家詳細(xì)介紹了Unity UGUI實現(xiàn)滑動翻頁,直接跳轉(zhuǎn)頁數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04
C#實現(xiàn)JSON解析器MojoUnityJson功能(簡單且高效)
MojoUnityJson 是使用C#實現(xiàn)的JSON解析器 ,算法思路來自于游戲引擎Mojoc的C語言實現(xiàn) Json.h。這篇文章主要介紹了C#實現(xiàn)JSON解析器MojoUnityJson的方法,需要的朋友可以參考下2018-01-01

