自学内容网 自学内容网

C#中压缩文件夹,及其内容

压缩包格式,本文主要用于说明如何使用代码 文件或文件夹压缩为 zip压缩包及其解压操作,
下面分两个版本进行实现

1.简单版本

   bool DoCompressDirectoryInfo(string folderPath)
   {
       try
       {
           var zipFilePath = $"{folderPath}.zip";
           var directoryInfo = new DirectoryInfo(zipFilePath);
           if (directoryInfo.Exists)
           {
               directoryInfo.Delete();
           }
           if (directoryInfo.Parent != null)
           {
               directoryInfo = directoryInfo.Parent;
           }

           System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, zipFilePath, CompressionLevel.Optimal, false);
           return true;
       }
       catch (Exception ex)
       {
           _logger.LogError(ex, $"压缩文件失败,{folderPath}!");
           return false;
       }
   }

2.第二种复杂版本

帮助类

class FolderCompressor
{

 public stati  bool DoCompressDirectoryInfo(string folderPath)
  {
      try
      {
          var zipFilePath = $"{folderPath}.zip";

          FolderCompressor.CompressFolder(folderPath, zipFilePath);
          return true;
      }
      catch (Exception ex)
      {
          _logger.LogError(ex, $"压缩文件失败,{folderPath}!");
          return false;
      }
  }

    public static void CompressFolder(string sourceFolderPath, string destinationZipFilePath)
    {
        using FileStream zipToOpen = new FileStream(destinationZipFilePath, FileMode.Create);
        using ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create);
        string currentPath = sourceFolderPath;
        AddFiles(archive, "", currentPath);
    }

    private static void AddFiles(ZipArchive archive, string currentPath, string sourceFolderPath)
    {
        var files = Directory.GetFiles(sourceFolderPath);

        foreach (string file in files)
        {
            // 获取文件的相对路径  
            string filePath = Path.GetFullPath(file);
            string relativePath = filePath.Substring(sourceFolderPath.Length).TrimStart(Path.DirectorySeparatorChar);

            // 将文件添加到ZIP存档  
            var readOnlyEntry = archive.CreateEntry(Path.Combine(currentPath, relativePath));

            using var fileToCompress = File.OpenRead(file);
            using var entryStream = readOnlyEntry.Open();
            fileToCompress.CopyTo(entryStream);
        }

        // 递归处理子文件夹  
        string[] directories = Directory.GetDirectories(sourceFolderPath);

        foreach (string dir in directories)
        {
            string folderName = Path.GetFileName(dir);
            AddFiles(archive, Path.Combine(currentPath, folderName), dir);
        }
    }
}

调用时候最好用 DoCompressDirectoryInfo方法


原文地址:https://blog.csdn.net/weixin_43542114/article/details/140612163

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!