ในบทช่วยสอนแบบทีละขั้นตอนนี้ คุณจะได้เรียนรู้วิธีสร้างไฟล์ ZIP ในหน่วยความจำด้วยภาษา C# คุณต้องดำเนินการตามขั้นตอนง่าย ๆ เพื่อให้สามารถสร้างไฟล์ ZIP ในหน่วยความจำได้
ขั้นตอนในการสร้างไฟล์ ZIP ในหน่วยความจำใน C#
- เพิ่มการอ้างอิงแพ็คเกจ NuGet Aspose.ZIP for .NET ไปยังโซลูชัน
- เพิ่มโดยใช้คำสั่ง Aspose.Zip ในไฟล์รหัส Program.cs
- สมัครใบอนุญาตสำหรับ Aspose.ZIP API โดยใช้วิธี License.SetLicense
- รับไฟล์เดียวหรือทั้งหมดจากโฟลเดอร์ที่อยู่บนดิสก์ & เก็บเส้นทางไว้ในอาร์เรย์สตริง
- สร้างวัตถุของ Archive Class ในหน่วยความจำ
- สำหรับแต่ละไฟล์ ให้สร้างโหนด ArchiveEntry ใน ZIP Archive
- บันทึกหรือคัดลอกอินสแตนซ์ ZIP Archive ไปยัง MemoryStream
ตัวอย่างโค้ด C# ต่อไปนี้สามารถใช้ในแอปพลิเคชัน .NET ของคุณเพื่อบีบอัดไฟล์ทั้งหมดในโฟลเดอร์บนดิสก์ไปยัง ZIP file format จากนั้นเก็บไฟล์ ZIP ไว้ในอ็อบเจ็กต์สตรีมหน่วยความจำ
รหัสเพื่อสร้างไฟล์ ZIP ในหน่วยความจำใน C
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 และเขียนเนื้อหาทั้งหมดของโฟลเดอร์ในหน่วยความจำในรูปแบบบีบอัด หลังจากนั้น คุณสามารถสร้างไฟล์ ZIP ใหม่จาก MemoryStream C# และบันทึกลงในดิสก์ เมื่อไฟล์เก็บถาวรถูกสร้างขึ้นใหม่บนระบบไฟล์ คุณจะสามารถ แตกไฟล์ ZIP โดยใช้ C# รหัสได้