首页 > 其他分享 >压缩文件帮助类

压缩文件帮助类

时间:2023-10-18 09:45:19浏览次数:26  
标签:帮助 archive zipArchiveEntry 压缩文件 var new FullName public

核心代码

  public class ZipHelper
  {
      #region   基础参数
      public delegate void UnZipProgressEventHandler(object sender, UnZipProgressEventArgs e);
      public event UnZipProgressEventHandler unZipProgress;

      public delegate void CompressProgressEventHandler(object sender, CompressProgressEventArgs e);
      public event CompressProgressEventHandler compressProgress;

      #endregion

      #region   公有方法
      /// <summary>
      /// 创建 zip 存档,该文档包含指定目录的文件和子目录(单个目录)。
      /// </summary>
      /// <param name="sourceDirectoryName">将要压缩存档的文件目录的路径,可以为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
      /// <param name="destinationArchiveFileName">将要生成的压缩包的存档路径。</param>
      /// <param name="compressionLevel">指示压缩操作是强调速度还是强调压缩大小的枚举值</param>
      /// <param name="includeBaseDirectory">压缩包中是否包含父目录</param>
      /// <returns>返回结果(true:表示成功)</returns>
      public bool CreatZip(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel = CompressionLevel.NoCompression, bool includeBaseDirectory = true)
      {
          int i = 1;
          try
          {
              if (Directory.Exists(sourceDirectoryName))
                  if (!File.Exists(destinationArchiveFileName))
                  {
                      ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory);
                  }
                  else
                  {
                      var toZipFileDictionaryList = GetAllDirList(sourceDirectoryName, includeBaseDirectory);
                      using (var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update))
                      {
                          var count = toZipFileDictionaryList.Keys.Count;
                          foreach (var toZipFileKey in toZipFileDictionaryList.Keys)
                          {
                              if (toZipFileKey != destinationArchiveFileName)
                              {
                                  var toZipedFileName = Path.GetFileName(toZipFileKey);
                                  var toDelArchives = new List<ZipArchiveEntry>();
                                  foreach (var zipArchiveEntry in archive.Entries)
                                  {
                                      if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
                                      {
                                          i++;
                                          compressProgress(this, new CompressProgressEventArgs { Size = zipArchiveEntry.Length, Count = count, Index = i, Path = zipArchiveEntry.FullName, Name = zipArchiveEntry.Name });
                                          toDelArchives.Add(zipArchiveEntry);
                                      }
                                  }

                                  foreach (var zipArchiveEntry in toDelArchives)
                                      zipArchiveEntry.Delete();
                                  archive.CreateEntryFromFile(toZipFileKey, toZipFileDictionaryList[toZipFileKey], compressionLevel);
                              }
                          }
                      }
                  }
              else if (File.Exists(sourceDirectoryName))
                  if (!File.Exists(destinationArchiveFileName))
                      ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, false);
                  else
                  {
                      using (var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update))
                      {
                          if (sourceDirectoryName != destinationArchiveFileName)
                          {
                              var toZipedFileName = Path.GetFileName(sourceDirectoryName);
                              var toDelArchives = new List<ZipArchiveEntry>();
                              var count = archive.Entries.Count;
                              foreach (var zipArchiveEntry in archive.Entries)
                              {
                                  if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
                                  {
                                      i++;
                                      compressProgress(this, new CompressProgressEventArgs { Size = zipArchiveEntry.Length, Count = count, Index = i, Path = zipArchiveEntry.FullName, Name = zipArchiveEntry.Name });
                                      toDelArchives.Add(zipArchiveEntry);
                                  }
                              }

                              foreach (var zipArchiveEntry in toDelArchives)
                                  zipArchiveEntry.Delete();
                              archive.CreateEntryFromFile(sourceDirectoryName, toZipedFileName, compressionLevel);
                          }
                      }
                  }
              else
                  return false;
              return true;
          }
          catch (Exception ex)
          {
              return false;
          }
      }

      /// <summary>
      /// 创建 zip 存档,该存档包含指定目录的文件和目录(多个目录)
      /// </summary>
      /// <param name="sourceDirectoryName">将要压缩存档的文件目录的路径。</param>
      /// <param name="destinationArchiveFileName">将要生成的压缩包的存档路径。</param>
      /// <param name="compressionLevel">指示压缩操作是强调速度还是压缩大小的枚举值</param>
      /// <returns>返回结果(true:表示成功)</returns>
      public bool CreatZip(Dictionary<string, string> sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
      {
          int i = 1;
          try
          {
              using (FileStream zipToOpen = new FileStream(destinationArchiveFileName, FileMode.OpenOrCreate))
              {
                  using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                  {
                      foreach (var toZipFileKey in sourceDirectoryName.Keys)
                      {
                          if (toZipFileKey != destinationArchiveFileName)
                          {
                              var toZipedFileName = Path.GetFileName(toZipFileKey);
                              var toDelArchives = new List<ZipArchiveEntry>();
                              var count = archive.Entries.Count;
                              foreach (var zipArchiveEntry in archive.Entries)
                              {
                                  if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
                                  {
                                      i++;
                                      compressProgress(this, new CompressProgressEventArgs { Size = zipArchiveEntry.Length, Count = count, Index = i, Path = toZipedFileName });
                                      toDelArchives.Add(zipArchiveEntry);
                                  }
                              }
                              foreach (var zipArchiveEntry in toDelArchives)
                                  zipArchiveEntry.Delete();
                              archive.CreateEntryFromFile(toZipFileKey, sourceDirectoryName[toZipFileKey], compressionLevel);
                          }
                      }
                  }
              }
              return true;
          }
          catch (Exception)
          {
              return false;
          }
      }

      /// <summary>
      /// 递归删除磁盘上的指定文件夹目录及文件
      /// </summary>
      /// <param name="baseDirectory">需要删除的文件夹路径</param>
      /// <returns>返回结果(true:表示成功)</returns>
      public bool DeleteFolder(string baseDirectory)
      {
          var successed = true;
          try
          {
              if (Directory.Exists(baseDirectory)) //如果存在这个文件夹删除之 
              {
                  foreach (var directory in Directory.GetFileSystemEntries(baseDirectory))
                      if (File.Exists(directory))
                          File.Delete(directory); //直接删除其中的文件  
                      else
                          successed = DeleteFolder(directory); //递归删除子文件夹 
                  Directory.Delete(baseDirectory); //删除已空文件夹     
              }
          }
          catch (Exception)
          {
              successed = false;
          }
          return successed;
      }

      /// <summary>
      /// 递归获取磁盘上的指定目录下所有文件的集合,返回类型是:字典[文件名,要压缩的相对文件名]
      /// </summary>
      /// <param name="strBaseDir">需要递归的目录路径</param>
      /// <param name="includeBaseDirectory">是否包含本目录(false:表示不包含)</param>
      /// <param name="namePrefix">目录前缀</param>
      /// <returns>返回当前递归目录下的所有文件集合</returns>
      public Dictionary<string, string> GetAllDirList(string strBaseDir, bool includeBaseDirectory = false, string namePrefix = "")
      {
          var resultDictionary = new Dictionary<string, string>();
          var directoryInfo = new DirectoryInfo(strBaseDir);
          var directories = directoryInfo.GetDirectories();
          var fileInfos = directoryInfo.GetFiles();
          if (includeBaseDirectory)
              namePrefix += directoryInfo.Name + "\\";
          foreach (var directory in directories)
              resultDictionary = resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix)).ToDictionary(k => k.Key, k => k.Value); //FullName是某个子目录的绝对地址
          foreach (var fileInfo in fileInfos)
              if (!resultDictionary.ContainsKey(fileInfo.FullName))
                  resultDictionary.Add(fileInfo.FullName, namePrefix + fileInfo.Name);
          return resultDictionary;
      }

      /// <summary>
      /// 解压Zip文件,并覆盖保存到指定的目标路径文件夹下
      /// </summary>
      /// <param name="zipFilePath">将要解压缩的zip文件的路径</param>
      /// <param name="unZipDir">解压后将zip中的文件存储到磁盘的目标路径</param>
      /// <returns>返回结果(true:表示成功)</returns>
      public bool UnZip(string zipFilePath, string unZipDir)
      {
          bool resualt;
          try
          {
              unZipDir = unZipDir.EndsWith(@"\") ? unZipDir : unZipDir + @"\";
              var directoryInfo = new DirectoryInfo(unZipDir);
              if (!directoryInfo.Exists)
                  directoryInfo.Create();
              var fileInfo = new FileInfo(zipFilePath);
              if (!fileInfo.Exists)
                  return false;
              using (var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
              {
                  using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                  {
                      var count = archive.Entries.Count;
                      for (int i = 0; i < count; i++)
                      {
                          var entries = archive.Entries[i];
                          if (!entries.FullName.EndsWith("/"))
                          {
                              var entryFilePath = Regex.Replace(entries.FullName.Replace("/", @"\"), @"^\\*", "");
                              var filePath = directoryInfo + entryFilePath; //设置解压路径
                              unZipProgress(this, new UnZipProgressEventArgs { Size = entries.Length, Count = count, Index = i + 1, Path = entries.FullName, Name = entries.Name });
                              var content = new byte[entries.Length];
                              entries.Open().Read(content, 0, content.Length);
                              var greatFolder = Directory.GetParent(filePath);
                              if (!greatFolder.Exists)
                                  greatFolder.Create();
                              File.WriteAllBytes(filePath, content);
                          }
                      }
                  }
              }
              resualt = true;
          }
          catch (Exception)
          {
              resualt = false;
          }
          return resualt;
      }

      /// <summary>
      /// 获取Zip压缩包中的文件列表
      /// </summary>
      /// <param name="zipFilePath">Zip压缩包文件的物理路径</param>
      /// <returns>返回解压缩包的文件列表</returns>
      public List<string> GetZipFileList(string zipFilePath)
      {
          List<string> fList = new List<string>();
          if (!File.Exists(zipFilePath))
              return fList;
          try
          {
              using (var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
              {
                  using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                  {
                      foreach (var zipArchiveEntry in archive.Entries)
                          if (!zipArchiveEntry.FullName.EndsWith("/"))
                              fList.Add(Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"), @"^\\*", ""));
                  }
              }
          }
          catch (Exception)
          {

          }
          return fList;
      }

      #endregion


      #region   私有方法



      #endregion


  }//Class_end

  public class UnZipProgressEventArgs
  {
      public long Size { get; set; }

      public int Index { get; set; }

      public int Count { get; set; }

      public string Path { get; set; }

      public string Name { get; set; }

  }

  public class CompressProgressEventArgs
  {
      public long Size { get; set; }

      public int Index { get; set; }

      public int Count { get; set; }

      public string Path { get; set; }

      public string Name { get; set; }

  }

标签:帮助,archive,zipArchiveEntry,压缩文件,var,new,FullName,public
From: https://www.cnblogs.com/wml-it/p/17771331.html

相关文章

  • GPS帮助类
    核心代码publicclassGpsHelper{privateconstdoubleEARTH_RADIUS=6378137;///<summary>///计算两点位置的距离,返回两点的距离,单位米///该公式为GOOGLE提供,误差小于0.2米///</summary>///<paramname="lat1">第一点纬度</para......
  • 直播间频繁被封禁是什么原因?有什么方法能够减少违规?干货分享,希望能对正在做无人直播的
    你的直播间为什么频繁被判违规?特别是新手用户建议来看一下这篇文章,为了更好地理解这个问题,我们首先需要了解直播平台的检测原理。其实也很简单,就是对视频和音频进行抽帧跟之前的直播和其他的直播间进行对比,如果画面和语音重复度过高,就有可能被判定违规,下面就分享一下我自己做去重......
  • AI如何帮助Salesforce从业者找工作?
    在当今竞争激烈的就业市场中,找到满意的工作是一项艰巨的任务。成千上万的候选人竞争一个岗位,你需要利用一切优势从求职大军中脱颖而出。这就是AI的用武之地,特别是像ChatGPT这样的人工智能工具,可以成为你的秘密武器。本篇文章将探讨AI如何帮助你加快Salesforce求职速度。01即时......
  • ABAP:年份+月份搜索帮助
    *&---------------------------------------------------------------------**&包含ZPPR011_S01*&---------------------------------------------------------------------*SELECTION-SCREENBEGINOFBLOCKblk1WITHFRAMETITLETEXT-001.......
  • 使用C#在Windows上压缩文件
    使用C#通过Zip实现文件的压缩可以设置输出文件的路径也可以留空,留空则会在压缩文件创建一个同名的.压缩包可以设置压缩包的密码可以设置压缩包的加密方式(ASE-256),可以使用LZMA但是加密码会报错可以设置压缩包的格式(zip),可以使用7z但是加密码会报错添加了密码最大长度的限......
  • Python 压缩文件解压文件
    安装zipfilepip3installzipfile38pip3installzipfile37 f=zipfile.ZipFile("test.zip",mode="")//mode解压是r,压缩是w,追加压缩是a  压缩文件importzipfiledefzip_files(files,zip_name):zip=zipfile.ZipFile(zip_name,'w',zipfi......
  • 公园视频监控系统如何改造?人工智能又能提供哪些帮助?
    近日合肥市骆岗公园宣布正式开园,作为目前世界最大的城市公园,占地12.7万平方公里,如此壮观宏伟的建设,也吸引到了不少市民进行参观打卡。不管大型小型,城市里的公园都是随处可见的,那么,公园安防管控如何做到位?这是一个难题。在公园的安防视频监控方案方面,较为成熟的还属旭帆科技的智能......
  • 数据结构的思维导图(帮助梳理脉络)
    编辑......
  • Mojo帮助Python 的性能提升了近 250 倍
    导读AydynTairov是一名开源作者,也是Meta前工程师,他此前将GitHub上火热的纯C语言实现的llama2.c项目移植到了Python——llama2.py。近期 Mojo编程语言正式开放下载,并且声称比Python快68000倍。于是 AydynTairov马不停蹄地就开始将 llama2.py 移植到......
  • FASTNAT介绍和使用帮助
    下载地址Windows 64位MacOSX 64位Linux 64位Linux/ARM 32位 64位一、FastNat可为您解决的问题1.没公网服务器,需要发布本地的站点或网络程序到公网上,供他人访问;    此项功能大大方面开发人员进行远程调试,微信小程序等开发工作进行。2.需要远程到在其他网......