Listing Blobs using sdk runs into this exception "he stream was already consumed. It cannot be read again."

Ashish Gambhir 0 Reputation points Microsoft Employee
2025-10-16T19:34:29.49+00:00

I have the following code written to list blobs in a container as part of a controller api.


public async Task<IDictionary<string, string>> ListBlobsWithContentAsync(string container)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(container);

        var list = new Dictionary<string, string>();

        var containerClient = client.GetBlobContainerClient(container);

        var blobs = await ListBlobsFlatListingAsync(containerClient, 50);

        foreach (var blob in blobs)
        {
            var blobInfo = await GetBlobDownloadResultAsync(containerClient, blob).ConfigureAwait(false);

            using StreamReader reader = new(blobInfo.Value.Content);

            string blobContent = await reader.ReadToEndAsync().ConfigureAwait(false);

            list.Add(blob, blobContent);
        }

        return list;
    }


 private static async Task<IList<string>> ListBlobsFlatListingAsync(BlobContainerClient blobContainerClient,
        int? segmentSize)
    {
        var list = new List<string>();

        // Call the listing operation and return pages of the specified size.
        var resultSegment = blobContainerClient.GetBlobsAsync()
            .AsPages(default, segmentSize);

        // Enumerate the blobs returned for each page.
        await foreach (var blobPage in resultSegment)
        {
            foreach (var blobItem in blobPage.Values)
            {
                list.Add(blobItem.Name);
            }

        }

        return list;
    }


What is wrong with this code and what can I do to fix this?.

Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.