Listing Azure Blobs With Pagination

Viewed 490

Suppose I have thousands of files in Azure blob Storage and I want to get one page at a time (it is not good idea to load entire pages). But I couldn't get any idea how to proceed. I tried like this : List blobs with Azure Storage client libraries.

This is my code :

public async Task<BlobPageDto> GetBlobPageAsync
            (string containerName, int? segmentSize, string? continuationToken)
        {
            var blobPage = new BlobPageDto();

            try
            {

                BlobClient? blobClient = null;

                var client = new BlobContainerClient(_connectionString, containerName);
                await client.CreateIfNotExistsAsync();

                // Call the listing operation and return pages of the specified size.
                var resultSegment = client.GetBlobsAsync()
                    .AsPages(continuationToken, segmentSize);
                await foreach (var page in resultSegment)
                {
                    var blobItems = new List<BlobItemDto>();
                    foreach (var item in page.Values)
                    {
                        blobClient = client.GetBlobClient(item.Name);
                        string blobUrl = blobClient.Uri.ToString();

                        blobItems.Add(
                            new()
                            {
                                Name = item.Name,
                                Url = blobUrl
                            });
                    }

                    blobPage = new() { BlobItems = blobItems, ContinuationToken = page.ContinuationToken };
     break; //to get one page
                }
            }
            catch (RequestFailedException e)
            {
                
            }

            return blobPage;
        }

BlobItemDto.cs

public class BlobItemDto
    {
        public string Name { get; set; } = default!;
        public string Url { get; set; } = default!;
    }

BlobPageDto.cs

public class BlobPageDto
    {
        public IEnumerable<BlobItemDto>? BlobItems { get; set; }
        public string? ContinuationToken { get; set; }
    }

Update: From above code How I can achieve the pagination like this (since by using ContinuationToken I can only move forward): Pagination Demo

0 Answers
Related