PM> Install-Package SharpZipLib
public class SharpZipLibHelper { /// <summary> /// 单个文件进行压缩 /// </summary> /// <param name="fileName">待压缩的文件(绝对路径)</param> /// <param name="compressedFilePath">压缩后文件路径(绝对路径)</param> /// <param name="aliasFileName">压缩文件的名称(别名)</param> /// <param name="compressionLevel">压缩级别0-9,默认为5</param> /// <param name="blockSize">缓存大小,每次写入文件大小,默认为2048字节</param> /// <param name="isEncrypt">是否加密,默认加密</param> /// <param name="encryptPassword">加密的密码(为空的时候,不加密)</param> public static void CompressFile(string fileName, string compressedFilePath, string aliasFileName = "", int compressionLevel = 5, int blockSize = 2048, bool isEncrypt = true, string encryptPassword = "") { if (File.Exists(fileName) == false) throw new FileNotFoundException("未能找到当前文件!", fileName); try { string zipFileName = null; ///获取待压缩文件名称(带后缀名) string name = new FileInfo(fileName).Name; //拼接压缩后的文件地址 zipFileName = compressedFilePath + Path.DirectorySeparatorChar + (string.IsNullOrWhiteSpace(aliasFileName) ? name.Substring(0, name.LastIndexOf(".")) : aliasFileName) + ".zip"; ///使用using语句,资源使用完毕,自动释放(类需继承IDispose接口) using (FileStream fs = File.Create(zipFileName)) { using (ZipOutputStream outStream = new ZipOutputStream(fs)) { using (FileStream inStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { ///zip文档的一个条目 ZipEntry entry = new ZipEntry(name); ///压缩加密 if (isEncrypt) { outStream.Password = encryptPassword; } ///开始一个新的zip条目 outStream.PutNextEntry(entry); ///设置压缩级别 outStream.SetLevel(compressionLevel); ///缓冲区对象 byte[] buffer = new byte[blockSize]; ///读入缓冲区的总字节数,执行到最后读取为0时,则读取完毕 int sizeRead = 0; do { ///从流中读取字节,将该数据写入缓冲区 sizeRead = inStream.Read(buffer, 0, buffer.Length); ///将给定的缓冲区的数据写入当前zip文档条目 outStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } outStream.Finish(); } } } catch (System.Exception ex) { LogHelper.Write(ex.ToString()); } }
/// <summary> /// 压缩文件夹 /// </summary> /// <param name="directory">待压缩文件夹(绝对路径)</param> /// <param name="compressedDirectory">压缩后的文件夹(绝对路径)</param> /// <param name="aliasFileName">压缩文件的名称(别名)</param> /// <param name="isEncrypt">是否加密,默认加密</param> /// <param name="encryptPassword">加密的密码(为空不进行加密)</param> public static void CompressDirectory(string directory, string compressedDirectory, string aliasFileName, bool isEncrypt, string encryptPassword = "") { if (Directory.Exists(directory) == false) throw new DirectoryNotFoundException("未能找到当前路径!"); try { string zipFileName = null; ///获取待压缩文件名称 string name = new DirectoryInfo(directory).Name; zipFileName = compressedDirectory + Path.DirectorySeparatorChar + (string.IsNullOrWhiteSpace(aliasFileName) ? name : aliasFileName) + ".zip";
///使用using语句,资源使用完毕,自动释放(类需继承IDispose接口) using (FileStream fs = File.Create(zipFileName)) { using (ZipOutputStream outStream = new ZipOutputStream(fs)) { if (isEncrypt) { ///压缩文件加密 outStream.Password = encryptPassword; CompressTraversal(directory, outStream, ""); } } } } catch (System.Exception ex) { LogHelper.Write(ex.ToString()); } } /// <summary> /// 解压缩 /// </summary> /// <param name="compressedFile">压缩文件(绝对路径)</param> /// <param name="directory">目标路径(绝对路径)</param> /// <param name="encryptPassword">加密密码</param> /// <param name="overWrite">是否覆盖</param> /// <param name="blockSize">缓存大小,每次写入文件大小,默认2048字节</param> public static void UnCompressFile(string compressedFile, string directory, string encryptPassword, bool overWrite = true, int blockSize = 2048) { if (File.Exists(compressedFile) == false) throw new FileNotFoundException("未能找到压缩文件!", compressedFile); if (Directory.Exists(directory) == false) Directory.CreateDirectory(directory);
///判断路径最后一个字符是否为当前系统的DirectorySeparatorChar if (directory[directory.Length - 1] != Path.DirectorySeparatorChar) { directory += Path.DirectorySeparatorChar; } try { ///使用using语句,资源使用完毕,自动释放(类需继承IDispose接口) ///打开压缩文件进行读取 using (FileStream fs = File.OpenRead(compressedFile)) { ///创建压缩文件的输入流 using (ZipInputStream inStream = new ZipInputStream(fs)) { ///加密的密码 inStream.Password = encryptPassword; ZipEntry entry; while ((entry = inStream.GetNextEntry()) != null) { ///文件的父级目录名称 string directoryName = null; ///文件的名称,例如git\\git.exe string entryName = entry.Name;
if (string.IsNullOrWhiteSpace(entryName) == false) { directoryName = Path.GetDirectoryName(entryName) + Path.DirectorySeparatorChar; } ///获取文件名称,例如git.exe string name = Path.GetFileName(entryName); ///文件的父级目录的绝对路径 string newDirectory = directory + directoryName; if (Directory.Exists(newDirectory) == false) { Directory.CreateDirectory(newDirectory); }
if (string.IsNullOrWhiteSpace(name) == false) { ///文件的绝对路径 string fileName = directory + directoryName + name; ///如果覆盖解压或者本地不存在当前文件则进行解压缩 if (overWrite || File.Exists(fileName) == false) { using (FileStream fsWrite = File.Create(fileName)) { ///缓存区对象 byte[] buffer = new byte[blockSize]; ///读取的字节数 int sizeRead = 0; ///读取完成,解压完成 do { ///从流中读取字节,将此数据写入缓存区 sizeRead = inStream.Read(buffer, 0, buffer.Length); ///将字节写入文件流 fsWrite.Write(buffer, 0, buffer.Length); } while (sizeRead > 0); } } } } } } } catch (Exception ex) { LogHelper.Write(ex.ToString()); } } /// <summary> /// 递归遍历目录 /// </summary> private static void CompressTraversal(string directory, ZipOutputStream outStream, string parentDirectory) { ///判断路径最后一个字符是否为当前系统的DirectorySeparatorChar if (directory[directory.Length - 1] != Path.DirectorySeparatorChar) { directory += Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); var fileOrDirectory = Directory.GetFileSystemEntries(directory); ///遍历文件与目录 foreach (var item in fileOrDirectory) { ///判断是否为目录 if (Directory.Exists(item)) { CompressTraversal(item, outStream, (parentDirectory + item.Substring(item.LastIndexOf(Path.DirectorySeparatorChar) + 1) + Path.DirectorySeparatorChar)); } ///压缩文件 else { using (FileStream inStream = File.OpenRead(item)) { ///缓存区对象 byte[] buffer = new byte[inStream.Length]; ///从文件流中读取字节,将该数据写入缓存区 inStream.Read(buffer, 0, buffer.Length); ///获取该文件名称(附带文件目录结构,例如git\\git.exe) string fileName = parentDirectory + item.Substring(item.LastIndexOf(Path.DirectorySeparatorChar) + 1); ///创建zip条目 ZipEntry entry = new ZipEntry(fileName); entry.DateTime = DateTime.Now; entry.Size = inStream.Length;
crc.Reset(); crc.Update(buffer);
entry.Crc = crc.Value;
outStream.PutNextEntry(entry); outStream.Write(buffer, 0, buffer.Length); } } } }
}
//解压zip文件
public static byte[] UnZipFile(string _zip_file) { byte[] basebyte = new byte[0]; ZipEntry zipEntry = null; try { using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(_zip_file))) { while ((zipEntry = zipStream.GetNextEntry()) != null) { string fileName = Path.GetFileName(zipEntry.Name); using (Stream decompressedStream = new MemoryStream()) { byte[] buffer = new byte[204800]; while (true) { int size = zipStream.Read(buffer, 0, buffer.Length); if (size > 0) { byte[] fullbyte = new byte[basebyte.Length + size]; Array.Copy(basebyte, 0, fullbyte, 0, basebyte.Length); Array.Copy(buffer, 0, fullbyte, basebyte.Length, size); basebyte = fullbyte; } else { return basebyte; } } }
} return basebyte; } } catch (System.Exception ex) { //Debug.WriteLine(ex); return new byte[0]; } }
//解压GZ文件 public static byte[] UnGZFile(string zipfilename) { try { //创建压缩文件的输入流实例 using (GZipInputStream zipFile = new GZipInputStream(File.OpenRead(zipfilename))) { using (MemoryStream re = new MemoryStream(50000)) { int count; byte[] data = new byte[50000]; while ((count = zipFile.Read(data, 0, data.Length)) != 0) { re.Write(data, 0, count); } byte[] overarr = re.ToArray(); return overarr; }
} } catch (Exception ex) {
FileHelper.Write_Log(ex.Message, "解压gz文件"); return new byte[0]; } }