C#压缩与解压库及函数(zip格式,需要参数:压缩文件夹)
我使用的是SharpZipLib的压缩解压库,链接我就不提供了,下载引用就好了
关于压缩,啥也不说,直接先来代码(我的代码基本你可以直接拿去用,我都写成静态函数不用实例化)
压缩类
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 | public static class ZipClass { public static void ZipFileMain( string [] args) { string [] filenames = Directory.GetFiles(args[0]); Crc32 crc = new Crc32(); ZipOutputStream s = new ZipOutputStream(File.Create(args[1])); s.SetLevel(6); // 0 - store only to 9 - means best compression foreach ( string file in filenames) { //打开压缩文件 FileStream fs = File.OpenRead(file); byte [] buffer = new byte [fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); Directory.Delete(args[0], true ); } } |
关于参数的说明:ZipFileMain的参数是string[],第一个参数是压缩文件夹路径,第二个是压缩文件路径
解压缩
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 | public static class UnZipClass { public static void UnZip( string [] args) { ZipInputStream s = new ZipInputStream(File.OpenRead(args[0])); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null ) { string directoryName = Path.GetDirectoryName(args[1]); string fileName = Path.GetFileName(theEntry.Name); //生成解压目录 Directory.CreateDirectory(directoryName); if (fileName != String.Empty) { //解压文件到指定的目录 FileStream streamWriter = File.Create(args[1] + theEntry.Name); int size = 2048; byte [] data = new byte [2048]; while ( true ) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break ; } } streamWriter.Close(); } } s.Close(); File.Delete(args[0]); } } |
关于参数的说明:UnZip的参数是string[],第一个参数是压缩文件路径,第二个是压缩文件夹路径!
新人发帖,顶顶,大家多加我好友,交流交流技术,各位博客园大神多多指教!
posted on 2011-08-17 11:48 FrostStudio 阅读(838) 评论(2) 编辑 收藏 举报
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具