/// <summary> /// 压缩文件夹下所有文件或者文件夹 /// </summary> /// <param name="strFile">需要压缩的文件夹的 全路径</param> /// <param name="strZip">压缩后存放的 全路径(包括压缩文件名.zip)</param> public void ZipFile(string strFile, string strZip, ref double count, de_FileSize de_fileSize = null) { if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) { strFile += Path.DirectorySeparatorChar; } ZipOutputStream s = new ZipOutputStream(File.Create(strZip)); s.SetLevel(6); // 0 - store only to 9 - means best compression zip(strFile, s, strFile, ref count, de_fileSize); s.Finish(); s.Close(); }
/// <summary> /// 递归文件夹下是否有文件夹或者文件 并对文件进行压缩 /// </summary> /// <param name="strFile">需要压缩的文件夹的 全路径</param> /// <param name="s"></param> /// <param name="staticFile">获取需要压缩文件的后部分路径</param> private void zip(string strFile, ZipOutputStream s, string staticFile, ref double count, de_FileSize de_fileSize = null) { if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) { strFile += Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); //获取所有文件或者子目录 string[] filenames = Directory.GetFileSystemEntries(strFile); foreach (string file in filenames) { if (Directory.Exists(file)) //如果存在文件夹继续递归 { zip(file, s, staticFile, ref count, de_fileSize); //递归 } else // 否则直接压缩文件 { //打开压缩文件 FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1); //压缩文件 ZipEntry entry = new ZipEntry(tempfile); entry.DateTime = DateTime.Now; entry.Size = fs.Length; count += buffer.Length; if (de_fileSize != null) { de_fileSize(count); } fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } }