Writing Zip Files in-memory
suggest changeThe following example will return the byte[] data of a zipped file containing the files provided to it, without needing access to the file system.
public static byte[] ZipFiles(Dictionary<string, byte[]> files)
{
using (MemoryStream ms = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
ZipArchiveEntry orderEntry = archive.CreateEntry(file.Key); //create a file with this name
using (BinaryWriter writer = new BinaryWriter(orderEntry.Open()))
{
writer.Write(file.Value); //write the binary data
}
}
}
// leaveOpen: true keeps the stream open. The central directory is written on dispose, so dispose the archive before ToArray.
return ms.ToArray();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents