Search code examples
c#.netazureazure-storageazure-blob-storage

How to read all blobs from different path in one azure storage


I have followed microsoft tutorial about routing in azure IoT Hub, and now all my messages from iot hub are storaged in blobs in container. However each blob is in individual folder. For example messages send 3 nov 2018 19:53 are stored in xyz/00/2018/11/03/19/53 blob file. How can I get all blobs from all folders in container? I can't use CloudBlobContainer.ListBlobs() because I don't have this method. I have tried:

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference(storageContainerName);
        CloudBlob blob = blobContainer.GetBlockBlobReference("xyz/00/2018/11/03/20/15");
        MemoryStream stream = new MemoryStream();
        await blob.DownloadToStreamAsync(stream);
        return Encoding.UTF8.GetString(stream.ToArray());

and this code is returning content of blob located in xyz/00/2018/11/03/20/15 However if I try to iterate over Blobs using below code it returns only "https://{storageName}.blob.core.windows.net/{containerName}/{xyz}/"

            List<string> blobs = new List<string>();
        BlobResultSegment resultSegment = blobContainer.ListBlobsSegmentedAsync(null).Result;
        foreach (IListBlobItem item in resultSegment.Results)
        {
            if (item.GetType() == typeof(CloudBlockBlob))
            {
                CloudBlockBlob blob = (CloudBlockBlob)item;
                blobs.Add(blob.Name);
            }
            else if (item.GetType() == typeof(CloudPageBlob))
            {
                CloudPageBlob blob = (CloudPageBlob)item;
                blobs.Add(blob.Name);
            }
            else if (item.GetType() == typeof(CloudBlobDirectory))
            {
                CloudBlobDirectory dir = (CloudBlobDirectory)item;
                blobs.Add(dir.Uri.ToString());
            }
        }

        var result = String.Join(", ", blobs.ToArray());
        return result;

What I am missing here? How can I get every blob from container?


Solution

  • Use an overload of ListBlobsSegmentedAsync that accepts the useFlatBlobListing and set the value of useFlatBlobListing to true:

    useFlatBlobListing
    A boolean value that specifies whether to list blobs in a flat listing, or whether to list blobs hierarchically, by virtual directory.

    (source)