Creating Zip Files from Memory Stream C#

前端 未结 5 2130
执笔经年
执笔经年 2021-02-04 06:51

Basically the user should be able to click on one link and download multiple pdf files. But the Catch is I cannot create files on server or anywhere. Everything has to be in mem

5条回答
  •  既然无缘
    2021-02-04 07:35

    Below code is to get files from a directory in azure blob storage, merge in a zip and save it in azure blob storage again.

        var outputStream = new MemoryStream();
        var archive = new ZipArchive(outputStream, ZipArchiveMode.Create, true);
    
        CloudBlobDirectory blobDirectory = appDataContainer.GetDirectoryReference(directory);
        
        var blobs = blobDirectory.ListBlobs();
    
        foreach (CloudBlockBlob blob in blobs)
        {
            var fileArchive = archive.CreateEntry(Path.GetFileName(blob.Name),CompressionLevel.Optimal);
    
            MemoryStream blobStream = new MemoryStream();
            if (blob.Exists())
            {
                blob.DownloadToStream(blobStream);
                blobStream.Position = 0;
            }
    
            var open = fileArchive.Open();
            blobStream.CopyTo(open);
            blobStream.Flush();
            open.Flush();
            open.Close();
    
            if (deleteBlobAfterUse)
            {
                blob.DeleteIfExists();
            }
        }
        archive.Dispose();
    
        CloudBlockBlob zipBlob = appDataContainer.GetBlockBlobReference(zipFile);
    
        zipBlob.UploadFromStream(outputStream);
    

    Need the namespaces:

    • System.IO.Compression;
    • System.IO.Compression.ZipArchive;
    • Microsoft.Azure.Storage;
    • Microsoft.Azure.Storage.Blob;

提交回复
热议问题