في هذا البرنامج التعليمي خطوة بخطوة ، ستتعلم كيفية إنشاء ملف مضغوط في الذاكرة في C#. تحتاج إلى تنفيذ الخطوات البسيطة التالية لتتمكن من إنشاء أرشيف ZIP في الذاكرة.
خطوات إنشاء ملف مضغوط في الذاكرة في C#
- أضف مرجع حزمة Aspose.ZIP for .NET NuGet إلى الحل
- أضف باستخدام عبارة Aspose.Zip في ملف التعليمات البرمجية Program.cs
- تطبيق ترخيص Aspose.ZIP API باستخدام طريقة License.SetLicense
- الحصول على واحد أو كل الملفات من المجلد الموجود على القرص وتخزين مساراتهم في مجموعة سلسلة
- قم بإنشاء كائن Archive Class في الذاكرة
- لكل ملف ، أنشئ عقدة ArchiveEntry في أرشيف ZIP
- حفظ أو نسخ نسخة أرشيف مضغوط إلى MemoryStream
يمكن استخدام مثال رمز C# التالي في تطبيق .NET لضغط جميع الملفات في مجلد على القرص إلى ZIP file format ثم تخزين ملف ZIP في كائن دفق الذاكرة.
كود لإنشاء ملف مضغوط في الذاكرة في C#
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# وحفظه على القرص. بمجرد إعادة إنشاء الأرشيف على نظام الملفات ، يمكنك حينئذٍ رمز استخراج ملف مضغوط باستخدام C#.