以上是对ZipFile类的一些方法的解析,提供了该组件的一些方法的源码,至于源码的解读上难度不是很大,至于该组件的API,可以在下载DLL文件后,可以直接查看相应的方法和属性,在这里就不做详细的介绍。
三.DotNetZip组件使用实例:以上是对该组件的一些解析,接下来我们看看实例:
1.压缩ZIP文件:压缩ZIP文件 /// 支持多文件和多目录,或是多文件和多目录一起压缩 CompressMulti(List<string> list, string strZipName, bool isDirStruct) { if (list == null) { ); } if (string.IsNullOrEmpty(strZipName)) { throw new ArgumentNullException(strZipName); } try { (var zip = new ZipFile(Encoding.Default)) { foreach (var path in list) { fileName = Path.GetFileName(path); (Directory.Exists(path)) { (isDirStruct) { zip.AddDirectory(path, fileName); } else { //目录下的文件都压缩到Zip的根目录 zip.AddDirectory(path); } } if (File.Exists(path)) { zip.AddFile(path); } } //压缩 zip.Save(strZipName); return true; } } catch (Exception ex) { throw new Exception(ex.Message); } }
2.解压ZIP文件:解压ZIP文件 Decompression(string strZipPath, string strUnZipPath, bool overWrite) { if (string.IsNullOrEmpty(strZipPath)) { throw new ArgumentNullException(strZipPath); } if (string.IsNullOrEmpty(strUnZipPath)) { throw new ArgumentNullException(strUnZipPath); } try { var options = new ReadOptions { Encoding = Encoding.Default }; (var zip = ZipFile.Read(strZipPath, options)) { foreach (var entry in zip) { if (string.IsNullOrEmpty(strUnZipPath)) { strUnZipPath = strZipPath.Split().First(); } entry.Extract(strUnZipPath,overWrite ? ExtractExistingFileAction.OverwriteSilently : ExtractExistingFileAction.DoNotOverwrite); } return true; } } catch (Exception ex) { throw new Exception(ex.Message); } }
3.得到指定的输入流的ZIP压缩流对象:得到指定的输入流的ZIP压缩流对象 Stream ZipCompress(Stream sourceStream, ) { if (sourceStream == null) { ); } var compressedStream = new MemoryStream(); long sourceOldPosition = 0; try { sourceOldPosition = sourceStream.Position; sourceStream.Position = 0; using (var zip = new ZipFile()) { zip.AddEntry(entryName, sourceStream); zip.Save(compressedStream); compressedStream.Position = 0; } } catch (Exception ex) { throw new Exception(ex.Message); } finally { try { sourceStream.Position = sourceOldPosition; } catch (Exception ex) { throw new Exception(ex.Message); } } return compressedStream; }
4.得到指定的字节数组的ZIP解压流对象:得到指定的字节数组的ZIP解压流对象 /// 当前方法仅适用于只有一个压缩文件的压缩包,即方法内只取压缩包中的第一个压缩文件 Stream ZipDecompress(byte[] data) { Stream decompressedStream = new MemoryStream(); if (data == null) return decompressedStream; try { var dataStream = new MemoryStream(data); using (var zip = ZipFile.Read(dataStream)) { if (zip.Entries.Count > 0) { zip.Entries.First().Extract(decompressedStream); // Extract方法中会操作ms,后续使用时必须先将Stream位置归零,否则会导致后续读取不到任何数据 // 返回该Stream对象之前进行一次位置归零动作 decompressedStream.Position = 0; } } } catch(Exception ex) { throw new Exception(ex.Message); } return decompressedStream; }
四.总结: