.Net Core 多文件打包压缩

最近项目需要实现多文件打包的功能,尝试了一些方法,最后发现使用  ICSharpCode.SharpZipLib 最符合项目的要求。

具体实现如下:

1.在 Nuget 中安装  ICSharpCode.SharpZipLib

 

 

2.将要打包的文件放到同个文件夹进行压缩:

①压缩文件夹

 1         /// <summary>
 2         /// 压缩文件
 3         /// </summary>        
 4         /// <param name="fileName">压缩后获得的文件名</param>  
 5         public static bool CompressFile(string dir, out string fileName)
 6         {
 7             string dest = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\" + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".zip";   //默认压缩在桌面上
 8             if (!Directory.Exists(Path.GetDirectoryName(dest)))   //文件不存在就根据路径创建  E:\\test
 9                 Directory.CreateDirectory(Path.GetDirectoryName(dest));
10             using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(dest)))
11             {
12                 zipStream.SetLevel(6);   //压缩级别0-9  
13                 CreateZip(dir, zipStream);
14                 fileName = dest;
15                 zipStream.Finish();
16                 zipStream.Close();
17             }
18             return true;
19         }
20         /// <summary>
21         /// 压缩内容到 zipStream 流中 
22         /// </summary>        
23         /// <param name="source">源文件</param>  
24         /// <param name="zipStream">目标文件流(全路径+文件名+.zip)</param>
25 
26         private static void CreateZip(string source, ZipOutputStream zipStream)
27         {
28             Crc32 crc = new Crc32();
29             string[] files = Directory.GetFileSystemEntries(source);  //获得所有文件名称和目录名称
30             foreach (var file in files)
31             {
32                 if (Directory.Exists(file))    //如果是文件夹里有文件则递归
33                 {
34                     CreateZip(file, zipStream);
35                 }
36                 else    //如果不是则压缩
37                 {
38                     using (FileStream fs = File.OpenRead(file))
39                     {
40                         byte[] buffer = new byte[fs.Length];
41                         fs.Read(buffer, 0, buffer.Length);
42                         string tempFileName = file.Substring(file.LastIndexOf("\\") + 1);  //获得当前文件路径的文件名
43                         ZipEntry entry = new ZipEntry(tempFileName);
44                         entry.DateTime = DateTime.Now;
45                         entry.Size = fs.Length;
46                         fs.Close();
47                         crc.Reset();
48                         crc.Update(buffer);
49                         entry.Crc = crc.Value;
50                         zipStream.PutNextEntry(entry);
51                         zipStream.Write(buffer, 0, buffer.Length);
52                     }
53                 }
54             }
55         }
View Code

 

②将指定文件打包压缩 (可打包线上文件)

        /// <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);
                }
            }
        }
View Code

从文件路径读取文件名的方法:

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);
            }
        }
View Code

通过此方法生成的压缩包,所有文件都会显示在同一层。

 

③如果需要在文件中创建目录,需要在文件名称上指定文件路径

添加工具类:

 1     /// <summary>
 2     /// 文件对象
 3     /// </summary>
 4     public class FileItem
 5     {
 6         /// <summary>
 7         /// 文件名称
 8         /// </summary>
 9         public string FileName { get; set; }
10         /// <summary>
11         /// 文件路径
12         /// </summary>
13         public string FileUrl { get; set; }
14     }
View Code

压缩文件的方法:

 1         /// <summary>
 2         /// 打包线上线下文件
 3         /// </summary>
 4         /// <param name="zipName">压缩文件名称</param>
 5         /// <param name="fileList">文件列表</param>
 6         /// <param name="savepath">保存路径</param>
 7         public static string ZipFiles(string zipName, List<FileItem> fileList, out string error)
 8         {
 9             error = string.Empty;
10 
11             string path = string.Format("/files/zipFiles/{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
12             //文件保存目录
13             string directory = FileSavePath + path;
14             string url = FileHostUrl.TrimEnd('/') + path + zipName;
15             string savePath = directory + zipName;
16 
17             try
18             {
19                 if (!Directory.Exists(directory))
20                 {
21                     Directory.CreateDirectory(directory);
22                 }
23 
24                 using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(savePath)))
25                 {
26                     zipStream.SetLevel(9);   //压缩级别0-9  
27 
28                     foreach (var item in fileList)
29                     {
30                         byte[] buffer = new WebClient().DownloadData(item.FileUrl);
31                         ZipEntry entry = new ZipEntry(item.FileName);
32                         entry.DateTime = DateTime.Now;
33                         entry.Size = buffer.Length;
34                         zipStream.PutNextEntry(entry);
35                         zipStream.Write(buffer, 0, buffer.Length);
36                     }
37                 }
38             }
39             catch (Exception ex)
40             {
41                 error = "文件打包失败:" + ex.Message;
42             }
43 
44             return url;
45         }
View Code

 

调用参数示例:

{
  "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"
    }
  ]
}

生成的结果:

 

posted @ 2021-12-24 14:50  Nine_Jason  阅读(1918)  评论(0编辑  收藏  举报