写点什么

.NET 使用原生方法实现文件压缩和解压

作者:追逐时光者
  • 2025-10-20
    广东
  • 本文字数:3222 字

    阅读完需:约 11 分钟

前言

在.NET 中实现文件或文件目录压缩和解压可以通过多种方式来完成,包括使用原生方法(System.IO.Compression命名空间中的类)和第三方库(如:SharpZipLibSharpCompressK4os.Compression.LZ4等)。本文我们主要讲的是如何使用.NET原生方法System.IO.Compression命名空间中的类来对文件和文件夹进行压缩或解压缩(压缩格式.zip文件格式)。

System.IO.Compression 命名空间

包含为流提供基本压缩和解压缩服务的类。

包含的类

  • ZipFile:提供创建、解压缩和打开 zip 存档的静态方法。

  • ZipArchive:表示 Zip 存档格式中的一个压缩文件包。

  • ZipArchiveEntry:表示 zip 档案中的压缩文件。

  • DeflateStream:提供使用 Deflate 算法压缩和解压缩流的方法和属性。

  • GZipStream:使用 GZip 数据格式规范提供用于压缩和解压缩流的方法和属性。

  • BrotliStream:使用 Brotli 数据格式规范提供用于压缩和解压缩流的方法和属性。

  • ZipFileExtensions:为 ZipArchive 和 ZipArchiveEntry 类提供扩展方法。

  • ZLibStream:提供用于使用 zlib 数据格式规范压缩和解压缩流的方法和属性。

文件压缩的作用和场景

  • 节省存储空间:通过压缩文件,可以显著减小文件占用的磁盘空间。

  • 减少网络传输时间:在网络传输文件时,压缩文件可以减少传输时间,特别是在带宽受限或者对传输速度有要求的情况下,压缩文件可以提高传输效率。

  • 打包和分发文件:将多个文件或文件夹打包成一个压缩文件,便于整体传输、备份或者分发。这在软件发布、数据备份和文件传输中经常会用到。

  • 加密和保护文件:一些压缩工具支持对文件进行加密,可以保护文件内容不被未经授权的人看到或修改。

CompressionLevel(压缩级别)

用来指示压缩操作是强调速度还是强调压缩大小的值。

ZipArchiveMode(Zip 归档模式)

用来与 zip 存档条目进行交互的值。

创建.NET8 控制台应用

创建名为:FileCompDecompExercise的控制台应用。



指定文件压缩为.zip 文件

        static void Main(string[] args)        {            var sourceFilePath = @".\MySourceFile.xls"; //指定要压缩的文件路径(先创建对应.xls文件)            var zipSourceFilePath = @".\OutputFolder\ZipSourceFilePath.zip"; //压缩后文件存放路径
            //指定文件压缩为zip文件            CompressZipFile(sourceFilePath, zipSourceFilePath);            Console.WriteLine("操作完成");        }                /// <summary>        /// 指定文件压缩为zip文件        /// </summary>        /// <param name="sourceFilePath">指定要压缩的文件路径</param>        /// <param name="zipFilePath">指定压缩后的zip文件路径</param>        public static void CompressZipFile(string sourceFilePath, string zipFilePath)        {            //确保指定的路径中的目录存在            DirectoryInfo directoryInfo = new DirectoryInfo(zipFilePath);            if (directoryInfo.Parent != null)            {                directoryInfo = directoryInfo.Parent;            }
            if (!directoryInfo.Exists)            {                directoryInfo.Create();            }
            // 创建一个新的 Zip 存档并向其中添加指定的文件            using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Update))            {                archive.CreateEntryFromFile(sourceFilePath, Path.GetFileName(sourceFilePath));            }            Console.WriteLine("文件压缩完成");        }        
复制代码


指定文件夹压缩为.zip 文件

        static void Main(string[] args)        {            var sourceDirectory = @".\ZipFileDirectory";//指定压缩的文件目录(先在对应位置创建好)            var zipFilePath = @".\OutputFolder\Archive.zip"; //压缩后文件存放路径            CompressZipFileDirectory(sourceDirectory, zipFilePath);            Console.WriteLine("操作完成");        }                /// <summary>        /// 指定文件目录压缩为zip文件        /// </summary>        /// <param name="sourceDirectory">指定压缩的文件目录</param>        /// <param name="zipFilePath">压缩后文件存放路径</param>        public static void CompressZipFileDirectory(string sourceDirectory, string zipFilePath)        {            //确保指定的路径中的目录存在            DirectoryInfo directoryInfo = new DirectoryInfo(zipFilePath);            if (directoryInfo.Parent != null)            {                directoryInfo = directoryInfo.Parent;            }
            if (!directoryInfo.Exists)            {                directoryInfo.Create();            }
            //创建一个新的 .zip 文件并将文件夹内容压缩进去            ZipFile.CreateFromDirectory(sourceDirectory, zipFilePath, CompressionLevel.Optimal, false);            Console.WriteLine("文件目录压缩完成");        }

复制代码


解压.zip 文件到目标文件夹


        static void Main(string[] args)        {            var zipFilePath = @".\OutputFolder\Archive.zip"; //压缩后文件存放路径            string extractPath = @".\OutputFolder"; // 解压目标文件夹路径            //解压.zip文件到目标文件夹            ExtractZipFile(zipFilePath, extractPath);            Console.WriteLine("操作完成");        }
        /// <summary>        /// 解压.zip文件到目标文件夹        /// </summary>        /// <param name="zipFilePath">要解压的.zip文件路径</param>        /// <param name="extractPath">解压目标文件夹路径</param>        public static void ExtractZipFile(string zipFilePath, string extractPath)        {            if (!Directory.Exists(extractPath))            {                Directory.CreateDirectory(extractPath);            }
            // 提取 .zip 文件到指定文件夹            ZipFile.ExtractToDirectory(zipFilePath, extractPath);            Console.WriteLine("文件解压完成");        }
复制代码


本文示例源码

https://github.com/YSGStudyHards/DotNetExercises/tree/master/FileCompDecompExercise

参考文章

  • https://learn.microsoft.com/zh-cn/dotnet/api/system.io.compression.zipfile?view=net-8.0

发布于: 刚刚阅读数: 3
用户头像

不积跬步无以至千里,不积小流无以成江海! 2020-01-14 加入

微软MVP、华为云HCDE、华为云云享专家、51CTO专家博主、阿里云专家博主、博客园推荐博客、CSDN博客专家、腾讯云创作之星、掘金优秀创作者,一个热爱开源的全栈软件工程师,擅长C#、.NET、Vue等相关技术开发。

评论

发布
暂无评论
.NET使用原生方法实现文件压缩和解压_.net_追逐时光者_InfoQ写作社区