最近项目需要实现多文件打包的功能,尝试了一些方法,最后发现使用ICSharpCode.SharpZipLib 最符合项目的要求。
具体实现如下:
1.在 Nuget 中安装ICSharpCode.SharpZipLib
2.将要打包的文件放到同个文件夹进行压缩:
①压缩文件夹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/// <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 = 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); } } } } |
②将指定文件打包压缩 (可打包线上文件)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/// <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); } } } |
从文件路径读取文件名的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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); } } |
通过此方法生成的压缩包,所有文件都会显示在同一层。
③如果需要在文件中创建目录,需要在文件名称上指定文件路径
添加工具类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/// <summary> /// 文件对象 /// </summary> public class FileItem { /// <summary> /// 文件名称 /// </summary> public string FileName { get ; set ; } /// <summary> /// 文件路径 /// </summary> public string FileUrl { get ; set ; } } |
压缩文件的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
/// <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; } |
调用参数示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{ "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框架下C#实现多文件打包压缩的方法,希望对大家有所帮助。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/SuperJason/p/15727364.html