使用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); } } } } }