The official C# documentation states, that ZipFile.CreateFromDirectory()
creates a zipfile on the disk, as an intermediate step. However I need my system to run on devices where disk space is critical. Can I somehow just create the Zipfile in memory?
Avoid disk usage as an intermediate step for Zip Compression in C#
104 views Asked by AudioBubble At
2
There are 2 answers
0
On
While .NET 8 adds ZipFile.CreateFromDirectory
overloads that allow writing to a stream directly, you don't have to wait for that to come out to do that.
Instead, you can simply create a ZipArchive
with your stream and a ZipArchiveMode
of Create
, and then add entries to it:
public static void CreateZipArchive(string sourceDirectory, Stream destination)
{
using var archive = new ZipArchive(destination, ZipArchiveMode.Create, true);
foreach (var file in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories))
{
var entryName = Path.GetRelativePath(sourceDirectory, file).Replace(Path.DirectorySeparatorChar, '/');
archive.CreateEntryFromFile(file, entryName);
}
}
Use a MemoryStream
to write to memory.
.NET 8 adds exactly what you are looking or!! It adds new overloads as documented in Stream-based ZipFile methods: