/// <summary> /// 向压缩文件流中追加目录 /// </summary> /// <param name="zip">zip流</param> /// <param name="dir">目录名</param> /// <param name="path_len">根目录长度</param> /// <param name="fcp">进度事件</param> public static void AddDirectory(this ZipOutputStream zip, string dir, int path_len, FileCompressProgress fcp = null) { if (Directory.Exists(dir)) { zip.PutNextEntry(new ZipEntry(dir.Substring(path_len) + (Path.DirectorySeparatorChar == dir.Last() ? Char.MinValue : Path.DirectorySeparatorChar))); zip.CloseEntry(); foreach (var item in Directory.GetFiles(dir)) { zip.AddFile(item, path_len, fcp); //添加文件 } foreach (var item in Directory.GetDirectories(dir)) { zip.AddDirectory(item, path_len, fcp); //添加子目录 } } }
/// <summary> /// 对文件或目录进行压缩 /// </summary> /// <param name="names">待压缩文件或目录</param> /// <param name="outname">zip文件路径</param> /// <param name="level">压缩级别</param> /// <param name="fcp">压缩进度事件</param> public static void ZipCompress(string name, string outname, int level = Deflater.DEFLATED, FileCompressProgress fcp = null) { using (var outfs = File.Create(outname)) using (var zip = new ZipOutputStream(outfs)) //创建输出流 { zip.SetLevel(level); //设置压缩级别 var path = Path.GetDirectoryName(name); //获取文件/目录所在目录 var path_len = null == path ? 2 : path.Length; //设置添加路径起始字符,如果为根目录则为2 if (File.Exists(name)) { zip.AddFile(name, path_len, fcp);//添加文件 } else if (Directory.Exists(name)) { zip.AddDirectory(name, path_len, fcp);//添加目录 } zip.Flush(); } }
/// <summary> /// 对文件和目录进行压缩 /// </summary> /// <param name="names">待压缩文件集合及目录集合</param> /// <param name="outname">zip文件路径</param> /// <param name="level">压缩级别</param> /// <param name="fcp">压缩进度事件</param> public static void ZipCompress(List <string> names, string outname, int level = Deflater.DEFLATED, FileCompressProgress fcp = null) { outname = outname + ".zip"; //拼接输出文件名 using (var zip = new ZipOutputStream(File.Create(outname))) //创建输出流 { zip.SetLevel(level); //设置压缩级别 foreach (var item in names) //遍历 { var path = Path.GetDirectoryName(item); //获取文件/目录所在目录 var path_len = null == path ? 2 : path.Length; //设置添加路径起始字符,如果为根目录则为2 if (File.Exists(item)) { zip.AddFile(item, path_len, fcp);//添加文件 } else if (Directory.Exists(item)) { zip.AddDirectory(item, path_len, fcp);//添加目录 } } zip.Flush(); } }