/// <summary> /// 向包流中追加目录 /// </summary> /// <param name="tar">zip流</param> /// <param name="dir">目录名</param> /// <param name="path_len">根目录长度</param> /// <param name="fcp">进度事件</param> public static void AddDirectory(this TarOutputStream tar, string dir, int path_len, FileCompressProgress fcp = null) { if (Directory.Exists(dir)) { var head = new TarHeader(); head.Name = dir.Substring(path_len) + (Path.DirectorySeparatorChar == dir.Last() ? Char.MinValue : Path.DirectorySeparatorChar); head.ModTime = new DirectoryInfo(dir).LastWriteTimeUtc;//设置添加时间 tar.PutNextEntry(new TarEntry(head)); tar.CloseEntry(); foreach (var item in Directory.GetFiles(dir)) { tar.AddFile(item, path_len, fcp); //添加文件 } foreach (var item in Directory.GetDirectories(dir)) { tar.AddDirectory(item, path_len, fcp); //添加子目录 } } }
/// <summary> /// 打包Tar文件 /// </summary> /// <param name="names">要打包的目录或文件</param> /// <param name="outname">输出文件名</param> /// <param name="encod"></param> /// <param name="fcp"></param> public static void TarCompress(List <string> names, string outname, Encoding encod, FileCompressProgress fcp = null) { outname = outname + ".tar"; //拼接输出文件名 using (var zip = new TarOutputStream(File.Create(outname), encod)) //创建输出流 { 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(); } }