Svinjica
Svinjica

Reputation: 2519

Get all Blobs From Azure Storage using .NET Core 2.2

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

Upvotes: 7

Views: 3319

Answers (2)

Faesel Saeed
Faesel Saeed

Reputation: 199

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

Upvotes: 0

devNull
devNull

Reputation: 4219

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();
}

Upvotes: 11

Related Questions