使用SharpZIpLib写的压缩解压操作类
Posted guanglin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用SharpZIpLib写的压缩解压操作类相关的知识,希望对你有一定的参考价值。
使用SharpZIpLib写的压缩解压操作类,已测试。
public class ZipHelper { /// <summary> /// 压缩文件 /// </summary> /// <param name="directory"></param> /// <param name="targetPath"></param> public static void Zip(string directory, string targetPath) { using (var stream = new ZipOutputStream(File.OpenWrite(targetPath))) { Zip(directory, stream); } } private static void Zip(string directory, ZipOutputStream stream, string entryName = "") { //压缩文件 var files = Directory.GetFiles(directory); var buffer = new byte[4096]; foreach (string file in files) { var entry = new ZipEntry(entryName + Path.GetFileName(file)); entry.DateTime = DateTime.Now; stream.PutNextEntry(entry); using (var fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } //压缩子目录 var subDirectories = Directory.GetDirectories(directory); foreach (var subDirectory in subDirectories) { var subEntryName = Path.GetFileName(subDirectory) + "/"; var entry = new ZipEntry(subEntryName); entry.DateTime = DateTime.Now; stream.PutNextEntry(entry); stream.Flush(); Zip(subDirectory, stream, subEntryName); } } /// <summary> /// 解压zip文件 /// </summary> /// <param name="zipfilePath"></param> /// <param name="targetDirectory"></param> public static void Unzip(string zipfilePath, string targetDirectory) { if (!File.Exists(zipfilePath)) return; if(!Directory.Exists(targetDirectory)) Directory.CreateDirectory(targetDirectory); using (var stream = new ZipInputStream(File.OpenRead(zipfilePath))) { ZipEntry ent = null; while ((ent = stream.GetNextEntry()) != null) { if (string.IsNullOrEmpty(ent.Name)) continue; var path = Path.Combine(targetDirectory, ent.Name); path = path.Replace(‘/‘, ‘\‘); //创建目录 if (path.EndsWith("\")) { Directory.CreateDirectory(path); continue; } //创建文件 using (var fs = File.Create(path)) { var buffer = new byte[2048]; var lengthRead = 0; while ((lengthRead = stream.Read(buffer, 0, buffer.Length)) > 0) fs.Write(buffer, 0, lengthRead); } } } } }
以上是关于使用SharpZIpLib写的压缩解压操作类的主要内容,如果未能解决你的问题,请参考以下文章
使用 ICSharpCode.SharpZipLib.Zip压缩解压文件