C#实现多⽂件打包压缩(.Net Core)
最近项⽬需要实现多⽂件打包的功能,尝试了⼀些⽅法,最后发现使⽤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>
getsavefilename/// 压缩内容到 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);
}
}
通过此⽅法⽣成的压缩包,所有⽂件都会显⽰在同⼀层。
③如果需要在⽂件中创建⽬录,需要在⽂件名称上指定⽂件路径
添加⼯具类:
/// <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;
}
调⽤参数⽰例:
{
"zipName": "test.zip",
"fileList": [
{
"fileName": "123.png",
"fileUrl": "file.yidongcha/files/uploadfiles/image/2021/11/15/11c6de395fcc484faf4745ade62cf6e6.png"
},
{
"fileName": "123/456/789.jpg",
"fileUrl": "file.yidongcha/files/uploadfiles/image/2021/11/15/fe922b250acf4344b8ca4d2aad6e0355.jpg"
}
]
}
⽣成的结果:
以上所述是⼩编给⼤家介绍的.Net Core框架下C#实现多⽂件打包压缩的⽅法,希望对⼤家有所帮助。在此也⾮常感谢⼤家对⽹站的⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论