public byte[] PackToZip(IEnumerable<byte[]> files)
{
using (var archiveStream = new MemoryStream())
{
using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
{
foreach (var file in files)
{
var entryName = string.Format("entry name");
using (var entryStream = archive.CreateEntry(entryName).Open())
{
entryStream.Write(file, 0, file.Length);
}
}
}
return archiveStream.ToArray();
}
}
Is it safe, robust and efficient?
1 Answer 1
Every file within the ZIP archive has the same path, so it would be awkward when extracting them. You should either take another parameter enumerating the entry names, or generate them automatically using a counter.
There's a limit to the scalability of this code, since the input and output all have to fit within memory. That problem can be avoided by accepting Stream
s instead of byte[]
s for the input. You should also accept a Stream
to which the output should be written. You could still do everything in memory by using MemoryStream
s everywhere, but you would also have the flexibility to read from and write to files or the network.