public static bool IsZipFile(Stream stream, bool testExtract) { if (stream == null) { throw new ArgumentNullException("stream"); } bool flag = false; try { if (!stream.CanRead) { return false; } Stream @null = Stream.Null; using (ZipFile file = Read(stream, null, null, null)) { if (testExtract) { foreach (ZipEntry entry in file) { if (!entry.IsDirectory) { entry.Extract(@null); } } } } flag = true; } catch (IOException) { } catch (ZipException) { } return flag; }
2.Read()读取数据流:
private static ZipFile Read(Stream zipStream, TextWriter statusMessageWriter, Encoding encoding, EventHandler<ReadProgressEventArgs> readProgress) { if (zipStream == null) { throw new ArgumentNullException("zipStream"); } ZipFile zf = new ZipFile { _StatusMessageTextWriter = statusMessageWriter, _alternateEncoding = encoding ?? DefaultEncoding, _alternateEncodingUsage = ZipOption.Always }; if (readProgress != null) { zf.ReadProgress += readProgress; } zf._readstream = (zipStream.Position == 0L) ? zipStream : new OffsetStream(zipStream); zf._ReadStreamIsOurs = false; if (zf.Verbose) { zf._StatusMessageTextWriter.WriteLine("reading from stream..."); } ReadIntoInstance(zf); return zf; }
以上是对ZipFile类的一些方法的解析,提供了该组件的一些方法的源码,至于源码的解读上难度不是很大,至于该组件的API,可以在下载DLL文件后,可以直接查看相应的方法和属性,在这里就不做详细的介绍。
三.DotNetZip组件使用实例:
以上是对该组件的一些解析,接下来我们看看实例:
1.压缩ZIP文件:
/// <summary> /// 压缩ZIP文件 /// 支持多文件和多目录,或是多文件和多目录一起压缩 /// </summary> /// <param>待压缩的文件或目录集合</param> /// <param>压缩后的文件名</param> /// <param>是否按目录结构压缩</param> /// <returns>成功:true/失败:false</returns> public static bool CompressMulti(List<string> list, string strZipName, bool isDirStruct) { if (list == null) { throw new ArgumentNullException("list"); } if (string.IsNullOrEmpty(strZipName)) { throw new ArgumentNullException(strZipName); } try { //设置编码,解决压缩文件时中文乱码 using (var zip = new ZipFile(Encoding.Default)) { foreach (var path in list) { //取目录名称 var fileName = Path.GetFileName(path); //如果是目录 if (Directory.Exists(path)) { //按目录结构压缩 if (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文件: