123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302 |
- 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
- {
- /// <summary>
- /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
- /// </summary>
- /// <param name="dirPath">被压缩的文件夹夹路径</param>
- /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param>
- /// <param name="err">出错信息</param>
- /// <returns>是否压缩成功</returns>
- 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;
- }
- }
- /// <summary>
- /// 重载一个方法
- /// </summary>
- /// <param name="dirPath"></param>
- /// <param name="zipFilePath"></param>
- /// <param name="filtration">过滤 指定后缀数据</param>
- /// <param name="maxSize">限制大小 byte 1m=1024*1024 1kb=1024b 根据单个文件大小,进行模糊设置</param>
- /// <exception cref="Exception"></exception>
- public static List<string> 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<string> zips = new List<string>();
- try
- {
- List<string> filenames = Directory.GetFiles(dirPath).ToList();
- int allFileNames = filenames.Count;
- List<string> tempFile = new List<string>();
- 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;
- }
- }
- /// <summary>
- /// 功能:解压zip格式的文件。
- /// </summary>
- /// <param name="zipFilePath">压缩文件路径</param>
- /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
- /// <param name="err">出错信息</param>
- /// <returns>解压是否成功</returns>
- 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<ZipItem> 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;
- }
- }
- }
|