Šioje nuoseklioje pamokoje sužinosite, kaip sukurti ZIP failą atmintyje C#. Turite atlikti šiuos paprastus veiksmus, kad galėtumėte sukurti ZIP archyvą atmintyje.
Veiksmai, kaip sukurti ZIP failą atmintyje C#
- Prie sprendimo pridėkite Aspose.ZIP for .NET NuGet paketo nuorodą
- Pridėkite naudodami Aspose.Zip teiginį Program.cs kodo faile
- Pateikite Aspose.ZIP API licenciją naudodami License.SetLicense metodą
- Gaukite vieną arba visus failus iš aplanko, esančio diske, ir išsaugokite jų kelius eilučių masyve
- Sukurkite Archive Class objektą atmintyje
- Kiekvienam failui ZIP archyve sukurkite ArchiveEntry mazgą
- Išsaugokite arba nukopijuokite ZIP archyvo egzempliorių į “MemoryStream”.
Šis C# kodo pavyzdys gali būti naudojamas jūsų .NET programoje, norint suspausti visus failus aplanke diske į ZIP file format ir išsaugoti ZIP failą atminties srauto objekte.
Kodas sukurti ZIP failą atmintyje 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 | |
} | |
} | |
} |
Taigi, šis C# kūrimo zip failas atminties konsolės programoje iš esmės padės konvertuoti aplanką į ZIP formatą ir įrašyti visą aplanko turinį į atmintį suspaustu formatu. Po to galite iš naujo sukurti ZIP failą iš MemoryStream C# ir išsaugoti diske. Kai archyvas bus iš naujo sukurtas failų sistemoje, galėsite koduoti išskleiskite ZIP failą naudodami C#.