在这个循序渐进的教程中,您将学习如何使用 C# 在内存中创建 ZIP 文件。您需要执行以下简单步骤才能在内存中创建 ZIP 存档。
在 C# 中在内存中创建 ZIP 文件的步骤
- 解决方案添加 Aspose.ZIP for .NET NuGet 包引用 2.在Program.cs代码文件中添加using Aspose.Zip语句
- 使用 License.SetLicense 方法为 Aspose.ZIP API 申请许可 4.从位于磁盘上的文件夹中获取单个或所有文件并将它们的路径存储在字符串数组中
- 在内存中创建 Archive Class 的对象
- 对于每个文件,在 ZIP Archive 中创建一个 ArchiveEntry 节点
- 将 ZIP Archive 实例保存或复制到 MemoryStream
以下 C# 代码示例可用于您的 .NET 应用程序,将磁盘上文件夹中的所有文件压缩为 ZIP file format,然后将 ZIP 文件存储在内存流对象中。
用 C# 在内存中创建 ZIP 文件的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
// Following namespace is required to Create ZIP File in Memory | |
using Aspose.Zip; | |
namespace CreateZipFileInMemory | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
License AsposeZipLicense = new License(); | |
// Load license from file system into memory stream | |
using (MemoryStream stream = new MemoryStream(File.ReadAllBytes("path to license.lic"))) | |
{ | |
// Set license prior to creating ZIP file in memory | |
AsposeZipLicense.SetLicense(stream); | |
} | |
#region C# code to create ZIP archive in memory | |
// Create MemoryStream instance | |
using (MemoryStream zipFileInMemory = new MemoryStream()) | |
{ | |
// Create empty Archive object for ZIP file | |
using (Aspose.Zip.Archive zipArchive = new Aspose.Zip.Archive()) | |
{ | |
// Get all files from a Folder and store their paths in string Array | |
string[] filesArray = Directory.GetFiles("ZIP all Files\\", "*.*", SearchOption.TopDirectoryOnly); | |
// Loop through the Array and create an ArchiveEntry against each file within the ZIP Archive | |
foreach (string fileDiskPath in filesArray) | |
{ | |
string[] folders = fileDiskPath.Split(new char[] { '\\' }); | |
string fileName = folders[folders.Length - 1]; | |
zipArchive.CreateEntry(fileName, fileDiskPath); | |
} | |
// Call Save method to create ZIP Archive in memory | |
zipArchive.Save(zipFileInMemory); | |
} | |
} | |
#endregion | |
} | |
} | |
} |
因此,此 C# 在内存控制台应用程序中创建 zip 文件本质上将帮助您将文件夹转换为 ZIP 格式,并将文件夹的全部内容以压缩格式写入内存。之后,您可以从 MemoryStream C# 重新创建 ZIP 文件并保存到磁盘。在文件系统上重新创建存档后,您可以使用 C# 提取 ZIP 文件 编码。