In this step-by-step tutorial, you will learn how to create ZIP file in memory in C#. You need to execute following simple steps to be able to create ZIP archive in memory.
Steps to Create ZIP File in Memory in C#
- Add Aspose.ZIP for .NET NuGet package reference to solution
- Add using Aspose.Zip statement in Program.cs code file
- Apply license for Aspose.ZIP API using License.SetLicense method
- Get single or all Files from Folder located on disk & store their paths in string array
- Create object of Archive Class in memory
- For each file, create an ArchiveEntry node in ZIP Archive
- Save or copy ZIP Archive instance to MemoryStream
The following C# code example can be used in your .NET application to compress all files in a folder on disk to ZIP file format and then store ZIP file in memory stream object.
Code to Create ZIP File in Memory in 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 | |
} | |
} | |
} |
So, this C# create zip file in memory console application will essentially help you to convert folder to ZIP format and write folder’s entire content in memory in compressed format. Afterwards, you can re-create ZIP file from MemoryStream C# and save to disk. Once the archive is re-created on file system, you can then extract ZIP file using C# code.