.Net Core 多文件打包压缩的实现代码

2022-04-16 09:18:49

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

具体实现如下:

1.在 Nuget 中安装 ICSharpCode.SharpZipLib

.Net Core 多文件打包压缩的实现代码

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>        /// 压缩内容到 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];                   cmfzVJwN     fs.Read(buffer, 0, buffer.Length);                        string tempFileName = file.Substring(file.LastIndexOf("\") + 1);  //获得当前文件路径的文件名                        ZipEntry entry = new ZipEntry(tempFileName);                 www.easck.com       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": "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 多文件打包压缩的实现代码

到此这篇关于.Net Core 多文件打包压缩的实现代码的文章就介绍到这了,更多相关.Net Core 多文件打包压缩内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!