I created a tiny project which provides a Web Api endpoint to download files from Azure Blob Storage as zip archive. In this article, I will explain some fo the important pieces.
Add Zip Archive Entry From Cloud Blob Directory
This is a private function in BlobStorageZipArchiveService. It loops through each item in the directory and creates an entry in zip archive. If the item itself is a directory, the function will call itself. So this is a recursive function.
Generate Zip Archive Stream
This function resides in BlobStorageZipArchiveService as well. We have to check if the container exists and also if the relative address contains any files before we create the zip archive. Otherwise, it will generate an empty archive file which is invalid. leaveOpen will keep the stream open, so we can read it later. The last statement reset stream position. If we forget to do that, controller will try to download from the end of the stream which has nothing and the API endpoint will freeze.
Blob Storage Zip Archive Controller
This is the final endpoint. We cannot use using when instantiate MemoryStream instance, otherwise it will close the stream before File method tries to read it. We also leave memoryStream to File method to close.