SharpZipLib压缩指定的目录
/// <summary> /// ZIP:压缩文件夹 /// </summary> /// <param name="DirectoryToZip">需要压缩的文件夹(绝对路径)</param> /// <param name="ZipedPath">压缩后的文件路径(绝对路径)</param> /// <param name="ZipedFileName">压缩后的文件名称(文件名,默认 同源文件夹同名)</param> /// <param name="IsEncrypt">是否加密(默认 加密)</param> public static void ZipDirectory(string DirectoryToZip, string ZipedPath, string ZipedFileName = "") { //如果目录不存在,则报错 if (!Directory.Exists(DirectoryToZip)) { throw new System.IO.FileNotFoundException("指定的目录: " + DirectoryToZip + " 不存在!"); } //文件名称(默认同源文件名称相同) string ZipFileName = string.IsNullOrEmpty(ZipedFileName) ? ZipedPath + "\\" + new DirectoryInfo(DirectoryToZip).Name + ".zip" : ZipedPath + "\\" + ZipedFileName + ".zip"; using (FileStream ZipFile = File.Create(ZipFileName)) { using (ZipOutputStream s = new ZipOutputStream(ZipFile)) { ZipSetp(DirectoryToZip, s, ""); } } } /// <summary> /// 递归遍历目录 /// </summary> private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory += Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); string[] filenames = Directory.GetFileSystemEntries(strDirectory); foreach (string file in filenames)// 遍历所有的文件和目录 { if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 { string pPath = parentPath; pPath += file.Substring(file.LastIndexOf("\\") + 1); pPath += "\\"; ZipSetp(file, s, pPath); } else // 否则直接压缩文件 { //打开压缩文件 using (System.IO.FileStream fs = File.OpenRead(file)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1); ZipEntry entry = new ZipEntry(fileName); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } }
需要nuget安装ICSharpCode.SharpZipLib
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)