如何在 C# 中压缩文件夹

这篇快速文章包含有关如何在 C# 中压缩文件夹的信息。它提供了在编写用于为文件夹创建 ZIP 文件的工具时要执行的详细步骤。 C# zip 文件夹 中的几行代码及其所有子文件夹中的文件,无需安装任何第三方工具。

在 C# 中压缩文件夹的步骤

  1. 从 NuGet 包管理器添加 Aspose.ZIP 以压缩文件夹
  2. 使用输出 ZIP 文件名实例化 FileStream 类对象
  3. 实例化一个 ZIP Archive 文件对象
  4. 通过提供目标文件夹名称在存档中创建条目
  5. 保存存档以创建包含所有文件和子文件夹的 ZIP 文件

这些步骤通过首先提供环境配置然后介绍为文件夹创建 ZIP 文件所需的所有主要类来详细描述该过程。到 zip 文件夹 C# 编码步骤之后给出了完整的理解。

C#中压缩文件夹的代码

using System.IO;
using Aspose.Zip;
namespace ZipFolderInCSharp
{
class Program
{
static void Main(string[] args) // Main function to zip a complete folder in CSharp
{
// Create and instantiate a license to zip as many files as required
// instead of 8 files only in the absence of the license
Aspose.Zip.License licZipFolder= new Aspose.Zip.License();
licZipFolder.SetLicense("Aspose.Zip.lic");
// Create a file stream object by providing the output zip file name
using (FileStream ZippedFolder = File.Open("AnimationImages.zip", FileMode.Create))
{
// Create a Zip archive file class object
using (Archive archiveFile = new Archive())
{
// Add all the files and folders recursively
archiveFile.CreateEntries("AnimationImages");
// Save the output ZIP file
archiveFile.Save(ZippedFolder);
}
}
System.Console.WriteLine("Done");
}
}
}

C# 中的这些代码行从文件夹 创建 ZIP 文件。有一些变体可以完成该任务,例如,您可以提供 DirectoryInfo 类对象作为输出 ZIP 文件的文件源,而不是提供目标文件夹名称。同样,您还可以设置一个标志以将根文件夹包含在输出 ZIP 文件中。

本教程指导我们压缩一个完整的文件夹。如果您有兴趣了解反向过程,即提取 ZIP 文件,请参阅 如何在 C# 中提取 ZIP 文件 上的文章。

 简体中文