Here a simple example of how to create an “in memory” zip file using c# and .Net Framework.
My real need is to send a mail attachment containing a lot of files stored into an Azure Blob Storage container, without having to write anything on the Web Server file system.
Here the code…
You have to add a reference to:
- System.IO.Compression
- System.IO.Compression.FileSystem
///
/// of all Memory Stream passed as parameters
///
/// files">
///
private static MemoryStreamcreateZip(ListMyFileInfo> files)
{
using (varmemoryStream = new MemoryStream())
{
using (vararchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
varentryFile = archive.CreateEntry(file.FileName);
using (varentryStream = entryFile.Open())
{
file.FileContent.Seek(0, SeekOrigin.Begin);
file.FileContent.CopyTo(entryStream);
}
}
}
returnmemoryStream;
}
}
///
/// MyFileInfo class stores the file name and its content
///
class MyFileInfo
{
public stringFileName { get; set; }
public MemoryStreamFileContent { get; set; }
}