Stream Azure Blob Files to Zip File in Azure Blob Storage using C#

Here’s a simple way to write multiple files already located in Azure Blob Storage to a zip file and write/save to Azure Blob Storage using C#. Only a single file will be in memory at once, so you can create very large zip files without any memory issues of downloading all blobs in memory.


This works with ZipArchive Mode set to Create, so you won’t be able to add files to an existing zip file. But you can always overwrite existing file with OpenWriteAsync(true) set to true.

Init Blob Service

BlobServiceClient _blobServiceClient = new BlobServiceClient("StorageConnectionString");

Get Container

public async Task<BlobContainerClient> GetContainer(string containerName)
{
   var container = _blobServiceClient.GetBlobContainerClient(containerName);
   await container.CreateIfNotExistsAsync(PublicAccessType.Blob);
   return container;
}

Get Blobs with optional prefix/folderName

public async Task<List<BlobItem>> GetBlobsInContainer(BlobContainerClient container, string folderName)
{
  var blobs = new List<BlobItem>();
  await foreach (var blob in container.GetBlobsAsync(prefix: folderName))
  {
    blobs.Add(blob);
  }

 return blobs;
}

Zip Blobs

public async Task ZipBlobs(BlobContainerClient container, List<BlobItem> blobs, string zipFileName)
{
  var zipBlob = container.GetBlockBlobClient(zipFileName);
  await using var ms = await zipBlob.OpenWriteAsync(true);
  using var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true);
  foreach (var blob in blobs)
  {
    var blobClient = container.GetBlobClient(blob.Name);
    var entry = zipArchive.CreateEntry(blobClient.Name, CompressionLevel.Fastest);
    await using var entryStream = entry.Open();
    await blobClient.DownloadToAsync(entryStream);
  }
}

Note: This approach works to append/write to an existing zip blob memory? I suspect this might have to download the existing blob entirely first in memory, which certainly ruins the approach. I think you’ll need to give it a try and monitor the memory.