U ovom vodiču korak po korak naučit ćete kako stvoriti ZIP datoteku u memoriji u C#. Morate izvršiti sljedeće jednostavne korake kako biste mogli stvoriti ZIP arhivu u memoriji.
Koraci za stvaranje ZIP datoteke u memoriji u C#
- Rješenju dodajte referencu paketa Aspose.ZIP for .NET NuGet
- Dodajte pomoću naredbe Aspose.Zip u datoteku koda Program.cs
- Primijenite licencu za Aspose.ZIP API pomoću metode License.SetLicense
- Dobijte jednu ili sve datoteke iz mape koja se nalazi na disku i pohranite njihove staze u niz nizova
- Stvorite objekt Archive Class u memoriji
- Za svaku datoteku kreirajte čvor ArchiveEntry u ZIP arhivi
- Spremite ili kopirajte instancu ZIP arhive u MemoryStream
Sljedeći primjer C# koda može se koristiti u vašoj .NET aplikaciji za komprimiranje svih datoteka u mapi na disku u ZIP file format i zatim pohranjivanje ZIP datoteke u objekt toka memorije.
Kod za stvaranje ZIP datoteke u memoriji u 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 | |
} | |
} | |
} |
Dakle, ova C# aplikacija za stvaranje zip datoteke u memorijskoj konzoli će vam u osnovi pomoći da pretvorite mapu u ZIP format i zapišete cijeli sadržaj mape u memoriju u komprimiranom formatu. Nakon toga, možete ponovno stvoriti ZIP datoteku iz MemoryStream C# i spremiti je na disk. Nakon što se arhiva ponovno stvori u datotečnom sustavu, možete izdvoji ZIP datoteku pomoću C# kodirati.