David Gard
David Gard

Reputation: 12097

Azure Storage - Get a list of blobs in a container with the v12 SDK for .NET

I'm trying to list blobs in an Azure Storage Account container using the Azure Blob storage client library v12 for .NET. However, I'm failing, and I suspect I'm just doing silly things.

I have a method in a class to get the blobs, which seems to work as expected -

public AsyncPageable<BlobItem> GetBlobs(BlobContainerClient container)
{
    return container.GetBlobsAsync();
}

When I pass those blobs to a new instance of another class I'm seeing some unexpected behaviour. In this class, I expect the GetItems method to populate List<Item> Items. However, the behaviour is intermittent, and seems to only work the first time I call the method after starting my app - after that, List<Item> Items is empty.

What am I doing wrong?

class GetBinResponseBody
{
    public HttpStatusCode StatusCode = HttpStatusCode.OK;
    public Bin Bin;
    public List<Item> Items;

    public GetBinResponseBody(BlobContainerClient container, AsyncPageable<BlobItem> blobs)
    {
        this.Bin = new Bin(container);
        this.GetItems(blobs);
    }

    public async void GetItems(AsyncPageable<BlobItem> blobs)
    {
        this.Items = new List<Item>();
        await foreach (BlobItem blob in blobs)
        {
            this.Items.Add(new Item(blob));
        }
    }
}

Just for completeness, here is the the Item class.

class Item
{
    public string Name;
    public string ContentType;

    public Item(BlobItem blob)
    {
        BlobItemProperties properties = blob.Properties;

        this.Name = blob.Name;
        this.ContentType = properties.ContentType;
    }

}

Upvotes: 0

Views: 861

Answers (1)

David Gard
David Gard

Reputation: 12097

After some further research I came across the Factory Pattern, and using that I am now seeing List<Item> Items correctly populated after every call.

class GetBinResponseBody : ResponseBody
{
    public Bin Bin;
    public List<Item> Items = new List<Item>();

    public static GetBinResponseBody CreateAsync(BlobContainerClient container, AsyncPageable<BlobItem> blobs)
    {
        return new GetBinResponseBody().InitializeAsync(container, blobs).Result;
    }

    private async Task<GetBinResponseBody> InitializeAsync(BlobContainerClient container, AsyncPageable<BlobItem> blobs)
    {
        this.Bin = new Bin(container);
        await foreach (BlobItem blob in blobs)
        {
            this.Items.Add(new Item(blob));
        }
        return this;
    }
}

Upvotes: 2

Related Questions