在日常开发中,我们经常需要对文件进行打包、压缩或解压操作。C# 提供了强大的 System.IO.Compression 命名空间,其中的 ZipArchive 类可以让我们轻松实现 ZIP 格式的压缩与解压缩功能。本教程将从零开始,带你一步步掌握 C# ZipArchive 压缩解压缩 的核心用法。
要使用 ZipArchive,你需要确保项目中包含以下命名空间:
using System.IO;using System.IO.Compression; 此外,如果你使用的是 .NET Framework(而非 .NET Core 或 .NET 5+),你可能还需要在项目中添加对 System.IO.Compression.FileSystem 程序集的引用。
下面是一个将多个文件压缩成一个 ZIP 文件的完整示例。我们将使用 ZipArchive 的 Create 模式。
public static void CreateZipFromFiles(string zipPath, string[] filePaths){ using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)) { foreach (string filePath in filePaths) { if (File.Exists(filePath)) { // 获取文件名(不含路径),作为 ZIP 中的条目名称 string fileName = Path.GetFileName(filePath); archive.CreateEntryFromFile(filePath, fileName); } } }} 调用方式:
string[] files = { @"C:\data\file1.txt", @"C:\data\image.png" };CreateZipFromFiles(@"C:\output\archive.zip", files); 解压 ZIP 文件同样简单。我们使用 ZipArchiveMode.Read 模式读取 ZIP,并将每个条目写入目标目录。
public static void ExtractZipToDirectory(string zipPath, string extractPath){ if (!Directory.Exists(extractPath)) Directory.CreateDirectory(extractPath); using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { // 防止路径遍历攻击(可选但推荐) string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName)); if (!destinationPath.StartsWith(Path.GetFullPath(extractPath) + Path.DirectorySeparatorChar)) throw new IOException("非法 ZIP 条目路径"); if (entry.FullName.EndsWith("/")) { // 是目录 Directory.CreateDirectory(destinationPath); } else { // 是文件 entry.ExtractToFile(destinationPath, overwrite: true); } } }} 调用方式:
ExtractZipToDirectory(@"C:\output\archive.zip", @"C:\extracted"); IOException、UnauthorizedAccessException 等异常。通过本教程,你已经掌握了 C# 文件压缩教程 的核心技能。无论是创建 ZIP 包还是解压现有文件,ZipArchive 都提供了简洁而强大的 API。记住,良好的错误处理和安全检查是生产环境必不可少的部分。
希望这篇关于 .NET Zip 操作 的指南对你有所帮助!如果你正在寻找更高级的功能(如加密、分卷压缩等),可以考虑使用 SharpZipLib 或 SharpCompress 等开源库。
最后,别忘了反复练习这些代码片段,真正掌握 C# ZipArchive 使用方法,让你的 .NET 应用具备完整的文件压缩能力!
本文由主机测评网于2025-12-27发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20251213036.html