Редактиране

Споделяне чрез


List blobs with .NET

This article shows how to list blobs using the Azure Storage client library for .NET.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for .NET. The steps include package installation, adding using directives, and creating an authorized client object. For details, see Get started with Azure Blob Storage and .NET.

Install packages

From your project directory, install packages for the Azure Blob Storage and Azure Identity client libraries using the dotnet add package command. The Azure.Identity package is needed for passwordless connections to Azure services.

dotnet add package Azure.Storage.Blobs
dotnet add package Azure.Identity

Add using directives

Add these using directives to the top of your code file:

using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;

Some code examples in this article might require additional using directives.

Create a client object

To connect an app to Blob Storage, create an instance of BlobServiceClient. The following example shows how to create a client object using DefaultAzureCredential for authorization:

public BlobServiceClient GetBlobServiceClient(string accountName)
{
    BlobServiceClient client = new(
        new Uri($"https://{accountName}.blob.core.windows.net"),
        new DefaultAzureCredential());

    return client;
}

You can register a service client for dependency injection in a .NET app.

You can also create client objects for specific containers or blobs. To learn more about creating and managing client objects, see Create and manage client objects that interact with data resources.

Authorization

The authorization mechanism must have the necessary permissions to list a blob. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher. To learn more, see the authorization guidance for List Blobs (REST API).

About blob listing options

When you list blobs from your code, you can specify a number of options to manage how results are returned from Azure Storage. You can specify the number of results to return in each set of results, and then retrieve the subsequent sets. You can specify a prefix to return blobs whose names begin with that character or string. And you can list blobs in a flat listing structure, or hierarchically. A hierarchical listing returns blobs as though they were organized into folders.

To list the blobs in a storage account, call one of these methods:

Manage how many results are returned

By default, a listing operation returns up to 5000 results at a time, but you can specify the number of results that you want each listing operation to return. The examples presented in this article show you how to return results in pages. To learn more about pagination concepts, see Pagination with the Azure SDK for .NET.

Filter results with a prefix

To filter the list of blobs, specify a string for the prefix parameter. The prefix string can include one or more characters. Azure Storage then returns only the blobs whose names start with that prefix.

Return metadata

You can return blob metadata with the results by specifying the Metadata value for the BlobTraits enumeration.

Flat listing versus hierarchical listing

Blobs in Azure Storage are organized in a flat paradigm, rather than a hierarchical paradigm (like a classic file system). However, you can organize blobs into virtual directories in order to mimic a folder structure. A virtual directory forms part of the name of the blob and is indicated by the delimiter character.

To organize blobs into virtual directories, use a delimiter character in the blob name. The default delimiter character is a forward slash (/), but you can specify any character as the delimiter.

If you name your blobs using a delimiter, then you can choose to list blobs hierarchically. For a hierarchical listing operation, Azure Storage returns any virtual directories and blobs beneath the parent object. You can call the listing operation recursively to traverse the hierarchy, similar to how you would traverse a classic file system programmatically.

Use a flat listing

By default, a listing operation returns blobs in a flat listing. In a flat listing, blobs are not organized by virtual directory.

The following example lists the blobs in the specified container using a flat listing, with an optional segment size specified, and writes the blob name to a console window.

private static async Task ListBlobsFlatListing(BlobContainerClient blobContainerClient, 
                                               int? segmentSize)
{
    try
    {
        // 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 (Page<BlobItem> blobPage in resultSegment)
        {
            foreach (BlobItem blobItem in blobPage.Values)
            {
                Console.WriteLine("Blob name: {0}", blobItem.Name);
            }

            Console.WriteLine();
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

The sample output is similar to:

Blob name: FolderA/blob1.txt
Blob name: FolderA/blob2.txt
Blob name: FolderA/blob3.txt
Blob name: FolderA/FolderB/blob1.txt
Blob name: FolderA/FolderB/blob2.txt
Blob name: FolderA/FolderB/blob3.txt
Blob name: FolderA/FolderB/FolderC/blob1.txt
Blob name: FolderA/FolderB/FolderC/blob2.txt
Blob name: FolderA/FolderB/FolderC/blob3.txt

Note

The sample output shown assumes that you have a storage account with a flat namespace. If you've enabled the hierarchical namespace feature for your storage account, directories are not virtual. Instead, they are concrete, independent objects. As a result, directories appear in the list as zero-length blobs.

For an alternative listing option when working with a hierarchical namespace, see List directory contents (Azure Data Lake Storage).

Use a hierarchical listing

When you call a listing operation hierarchically, Azure Storage returns the virtual directories and blobs at the first level of the hierarchy.

To list blobs hierarchically, call the BlobContainerClient.GetBlobsByHierarchy, or the BlobContainerClient.GetBlobsByHierarchyAsync method.

The following example lists the blobs in the specified container using a hierarchical listing, with an optional segment size specified, and writes the blob name to the console window.

private static async Task ListBlobsHierarchicalListing(BlobContainerClient container, 
                                                       string prefix, 
                                                       int? segmentSize)
{
    try
    {
        // Call the listing operation and return pages of the specified size.
        var resultSegment = container.GetBlobsByHierarchyAsync(prefix:prefix, delimiter:"/")
            .AsPages(default, segmentSize);

        // Enumerate the blobs returned for each page.
        await foreach (Page<BlobHierarchyItem> blobPage in resultSegment)
        {
            // A hierarchical listing may return both virtual directories and blobs.
            foreach (BlobHierarchyItem blobhierarchyItem in blobPage.Values)
            {
                if (blobhierarchyItem.IsPrefix)
                {
                    // Write out the prefix of the virtual directory.
                    Console.WriteLine("Virtual directory prefix: {0}", blobhierarchyItem.Prefix);

                    // Call recursively with the prefix to traverse the virtual directory.
                    await ListBlobsHierarchicalListing(container, blobhierarchyItem.Prefix, null);
                }
                else
                {
                    // Write out the name of the blob.
                    Console.WriteLine("Blob name: {0}", blobhierarchyItem.Blob.Name);
                }
            }

            Console.WriteLine();
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

The sample output is similar to:

Virtual directory prefix: FolderA/
Blob name: FolderA/blob1.txt
Blob name: FolderA/blob2.txt
Blob name: FolderA/blob3.txt

Virtual directory prefix: FolderA/FolderB/
Blob name: FolderA/FolderB/blob1.txt
Blob name: FolderA/FolderB/blob2.txt
Blob name: FolderA/FolderB/blob3.txt

Virtual directory prefix: FolderA/FolderB/FolderC/
Blob name: FolderA/FolderB/FolderC/blob1.txt
Blob name: FolderA/FolderB/FolderC/blob2.txt
Blob name: FolderA/FolderB/FolderC/blob3.txt

Note

Blob snapshots cannot be listed in a hierarchical listing operation.

List blob versions or snapshots

To list blob versions or snapshots, specify the BlobStates parameter with the Version or Snapshot field. Versions and snapshots are listed from oldest to newest.

The following code example shows how to list blob versions.

private static void ListBlobVersions(BlobContainerClient blobContainerClient, 
                                           string blobName)
{
    try
    {
        // Call the listing operation, specifying that blob versions are returned.
        // Use the blob name as the prefix. 
        var blobVersions = blobContainerClient.GetBlobs
            (BlobTraits.None, BlobStates.Version, prefix: blobName)
            .OrderByDescending(version => version.VersionId).Where(blob => blob.Name == blobName);

        // Construct the URI for each blob version.
        foreach (var version in blobVersions)
        {
            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobContainerClient.Uri)
            {
                BlobName = version.Name,
                VersionId = version.VersionId
            };

            if ((bool)version.IsLatestVersion.GetValueOrDefault())
            {
                Console.WriteLine("Current version: {0}", blobUriBuilder);
            }
            else
            {
                Console.WriteLine("Previous version: {0}", blobUriBuilder);
            }
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

Resources

To learn more about how to list blobs using the Azure Blob Storage client library for .NET, see the following resources.

REST API operations

The Azure SDK for .NET contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar .NET paradigms. The client library methods for listing blobs use the following REST API operation:

Client library resources

See also

  • This article is part of the Blob Storage developer guide for .NET. To learn more, see the full list of developer guide articles at Build your .NET app.