在本教程中,我们将向您展示如何在 C# 代码中提取 Zip 文件。您可以使用 C# 解压缩应用程序中的存档。此代码支持多种 zip or archive file formats,如 GZip、RAR、TAR、7Zip 等。
在 C# 中提取 Zip 文件的步骤
- 从 NuGet.org 安装 Aspose.Zip for .NET 包
- 在代码中包含 Aspose.Zip 命名空间
- 使用 SetLicense 方法设置 Aspose.Zip API 的许可证
- 将输入 Zip 文件加载到 FileStream 对象中
- 从文件流创建一个新的 Archive object
- 获取存档中的文件数并循环浏览存档条目
- 提取每个存档条目并将文件保存到磁盘
存档中的每个条目不仅包含文件,还包含文件的名称。我们使用 Name 属性来获取文件名,然后提取具有相同名称的文件。
在 C# 中提取 Zip 文件的代码
using System; | |
using System.IO; | |
using System.Text; | |
//Add reference to Aspose.Zip for .NET API | |
//Use following namespace to extract zip file | |
using Aspose.Zip; | |
namespace ExtractZipFile | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before extracting Zip file | |
//using Aspose.Zip for .NET | |
Aspose.Zip.License AsposeZipLicense = new Aspose.Zip.License(); | |
AsposeZipLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Open file from disk using a file stream | |
FileStream ZipFileToBeExtracted = File.Open("ZipFileToBeExtracted.zip", FileMode.Open); | |
//Load Zip file stream to Archive object | |
Archive ZipArchiveToExtract = new Archive(ZipFileToBeExtracted); | |
//Get number of files | |
int NumberOfFileInArchive = ZipArchiveToExtract.Entries.Count; | |
//Loop through the archive for each file | |
for(int FileCounter =0; FileCounter < NumberOfFileInArchive; FileCounter++) | |
{ | |
//Get each zip archive entry and extract the file | |
ArchiveEntry ArchiveFileEntry = ZipArchiveToExtract.Entries[FileCounter]; | |
string NameOfFileInZipEntry = ArchiveFileEntry.Name; | |
ArchiveFileEntry.Extract(NameOfFileInZipEntry); | |
} | |
} | |
} | |
} |
在上面的代码中,我们使用 FileStream 加载 Zip archive,然后将提取的输出文件保存在磁盘上。您还可以在 C# 中使用此代码将文件解压缩到内存中。当您在代码或应用程序中进一步需要这些文件并且不想保存到磁盘时,这会很有帮助。使用此代码,您可以在应用程序中轻松快速地创建自己的 C# Zip 提取器或作为独立实用程序。