Get all Blobs From Azure Storage using .NET Core 2.2

Viewed 2147

Very quick question regarding fetching list of blobs from Azure Storage (or to be more precise from container)

As I'm using .NET Core 2.2 and async streams are not allowed in C# 7.3 version:

 await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
    {
        Console.WriteLine("\t" + blobItem.Name);
    }

So I tried with something like this but without any luck (stabbing in the dark)

List<BlobItem> items = new List<BlobItem>();
Task.Factory.StartNew(async () => items.Add(await containerClient.GetBlobsAsync()));

So I'm wondering what's the alternative to await foreach syntax in C# v7.3

Thank you

2 Answers

The AsyncPageable<T> returned by GetBlobsAsync() exposes an IAsyncEnumerator<T> that you can use to iterate using a simple while loop:

Azure.AsyncPageable<Azure.Storage.Blobs.Models.BlobItem> blobs = containerClient.GetBlobsAsync();
IAsyncEnumerator<Azure.Storage.Blobs.Models.BlobItem> enumerator = blobs.GetAsyncEnumerator();
try
{
    while (await enumerator.MoveNextAsync())
    {
        Azure.Storage.Blobs.Models.BlobItem blob = enumerator.Current;
        // use blob
    }
}
finally
{
    await enumerator.DisposeAsync();
}

There is a more compact syntax available to do this than the while loop option,

AsyncPageable<SecretProperties> allSecretProperties = client.GetPropertiesOfSecretsAsync();

await foreach (SecretProperties secretProperties in allSecretProperties)
{
    Console.WriteLine(secretProperties.Name);
}

Example is taken from the azure sdk docks

Related