Forum Discussion

ford_sopris's avatar
ford_sopris
Copper Contributor
Jul 19, 2022

Azure Function to unzip blob to specific blob folder

If this is not the right group to post this, please let me know.  I am not much of a developer but have a need to extract a ZIP file that resides in a Blob Container into the same container in a specific folder, I would like that folder to be named the same of the zip filename.  I have found several Azure Function blobs that use the new file blob trigger but all of them simply extract all the files in a specific container.  I cannot for the life of me figure out how to tell it to save it in a specific folder and how to get it to pull the name of the file to name that folder.  Does anyone have a template or code they would be willing to share with me?  The reason I need this is due to the fact that Power Automate's "extract to ***" connectors have a limit of 100 files in the zip.  Of course my zip files have just over 100 files in them......

1 Reply

  • Try Azure Function Code (C#)

     

    using System.IO;
    using System.IO.Compression;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Specialized;
    
    public static class UnzipBlobFunction
    {
        [FunctionName("UnzipBlobFunction")]
        public static async Task Run(
            [BlobTrigger("input-container/{name}", Connection = "AzureWebJobsStorage")] Stream zipBlob,
            string name,
            ILogger log)
        {
            string zipFileNameWithoutExtension = Path.GetFileNameWithoutExtension(name);
            string outputContainerName = "input-container"; // same container
    
            var blobServiceClient = new BlobServiceClient(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));
            var containerClient = blobServiceClient.GetBlobContainerClient(outputContainerName);
    
            using (var archive = new ZipArchive(zipBlob))
            {
                foreach (var entry in archive.Entries)
                {
                    if (string.IsNullOrEmpty(entry.Name)) continue; // skip folders
    
                    string outputBlobPath = $"{zipFileNameWithoutExtension}/{entry.Name}";
                    var outputBlobClient = containerClient.GetBlobClient(outputBlobPath);
    
                    using (var entryStream = entry.Open())
                    using (var memoryStream = new MemoryStream())
                    {
                        await entryStream.CopyToAsync(memoryStream);
                        memoryStream.Position = 0;
                        await outputBlobClient.UploadAsync(memoryStream, overwrite: true);
                    }
    
                    log.LogInformation($"Extracted: {outputBlobPath}");
                }
            }
        }
    }

     

Resources