using ICSharpCode.SharpZipLib.Zip; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XYY.Common.Standard { public static class ZipHelper { /// /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// /// 被压缩的文件夹夹路径 /// 生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip /// 出错信息 /// 是否压缩成功 public static void ZipPath(string dirPath, string zipFilePath) { if (dirPath == string.Empty) { throw new Exception("要压缩的文件夹不能为空!"); } if (!Directory.Exists(dirPath)) { throw new Exception("要压缩的文件夹不存在!"); } //压缩文件名为空时使用文件夹名+.zip if (zipFilePath == string.Empty) { if (dirPath.EndsWith("\\")) { dirPath = dirPath.Substring(0, dirPath.Length - 1); } zipFilePath = dirPath + ".zip"; } try { string[] filenames = Directory.GetFiles(dirPath); using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string file in filenames) { ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } s.Finish(); s.Close(); } } catch { throw; } } /// /// 重载一个方法 /// /// /// /// 过滤 指定后缀数据 /// 限制大小 byte 1m=1024*1024 1kb=1024b 根据单个文件大小,进行模糊设置 /// public static List ZipPath(string dirPath, string zipFilePath, string filtration, int maxSize) { if (dirPath == string.Empty) { throw new Exception("要压缩的文件夹不能为空!"); } if (!Directory.Exists(dirPath)) { throw new Exception("要压缩的文件夹不存在!"); } //压缩文件名为空时使用文件夹名+.zip if (zipFilePath == string.Empty) { if (dirPath.EndsWith("\\")) { dirPath = dirPath.Substring(0, dirPath.Length - 1); } zipFilePath = dirPath + ".zip"; } List zips = new List(); try { List filenames = Directory.GetFiles(dirPath).ToList(); int allFileNames = filenames.Count; List tempFile = new List(); int count = 0; do { if (tempFile.Count > 0) { filenames.RemoveAll(x => tempFile.Contains(x)); tempFile.Clear(); } count++; string rootPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(@"\") + 1); string filePath = zipFilePath.Substring(zipFilePath.LastIndexOf(@"\") + 1, zipFilePath.Length - zipFilePath.LastIndexOf(@"\") - 1); zipFilePath = rootPath + filePath.Split(".")[0].Split("-")[0] + $"-{count}" + ".zip"; zips.Add(zipFilePath); using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); byte[] buffer = new byte[4096]; int totalLength = 0; foreach (string file in filenames) { if (!string.IsNullOrEmpty(filtration)) { if (file.Contains(filtration)) { continue; } } //过滤文件 ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); totalLength += sourceBytes; if (totalLength > maxSize) { break; } s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } //跳出循环 if (totalLength > maxSize) { break; } allFileNames--; tempFile.Add(file); } s.Finish(); s.Close(); } } while (allFileNames > 0); return zips; } catch { throw; } } /// /// 功能:解压zip格式的文件。 /// /// 压缩文件路径 /// 解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 /// 出错信息 /// 解压是否成功 public static void UnZipPath(string zipFilePath, string unZipDir) { if (zipFilePath == string.Empty) { throw new Exception("压缩文件不能为空!"); } if (!File.Exists(zipFilePath)) { throw new Exception("压缩文件不存在!"); } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); if (!unZipDir.EndsWith("\\")) unZipDir += "\\"; if (!Directory.Exists(unZipDir)) Directory.CreateDirectory(unZipDir); try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(unZipDir + directoryName); } if (!directoryName.EndsWith("\\")) directoryName += "\\"; if (fileName != string.Empty) { using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } }//while } } catch { throw; } } public static Stream ZipStream(IEnumerable streams) { MemoryStream ms = new MemoryStream(); ZipOutputStream s = new ZipOutputStream(ms); s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (var item in streams) { ZipEntry entry = new ZipEntry(item.FileName); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); int sourceBytes; do { sourceBytes = item.Stream.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } s.Finish(); ms.Position = 0; return ms; } //public static Stream WriteZip(params ZipItem[] streams) //{ // MemoryStream ms = new MemoryStream(); // ZipOutputStream zipOut = null; // 定义压缩输出流 // zipOut = new ZipOutputStream(ms); // 实例化压缩输出流对象,并指定压缩文件的输出路径 // for (int i = 0; i < streams.Length; i++) // { // zipOut.PutNextEntry(new ZipEntry(streams[i].FileName)); // 创建ZipEntry 每一个被压缩的文件都用ZipEntry表示,需要为每一个压缩后的文件设置名称 // zipOut.SetComment("这里是注释"); // 设置注释 // Stream fs = streams[i].Stream;//file.OpenRead();//定义输出流 // long dataLengthToRead = fs.Length; ////获取输出流总大小 // while (dataLengthToRead > 0) // { // 读取内容 // byte[] buffer = new byte[524288]; // int lengthRead = fs.Read(buffer, 0, buffer.Length);//读取的大小 // zipOut.Write(buffer, 0, lengthRead); // 压缩输出内容 // dataLengthToRead = dataLengthToRead - lengthRead; // } // fs.Close(); // 关闭输入流 // } // zipOut.Finish(); //完成压缩流 // //zipOut.Close(); // 关闭压缩输出流 // ms.Position = 0; // return ms; //} } public class ZipItem { public ZipItem(string fileName, Stream stream) { this.FileName = fileName; this.Stream = stream; } public string FileName { get; set; } public Stream Stream { get; set; } } }