Muokkaa

Jaa


Manage blob properties and metadata with .NET

In addition to the data they contain, blobs support system properties and user-defined metadata. This article shows how to manage system properties and user-defined metadata with 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 work with container properties or metadata. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher for the get operations, and Storage Blob Data Contributor or higher for the set operations. To learn more, see the authorization guidance for Set Blob Properties (REST API), Get Blob Properties (REST API), Set Blob Metadata (REST API), or Get Blob Metadata (REST API).

About properties and metadata

  • System properties: System properties exist on each Blob storage resource. Some of them can be read or set, while others are read-only. Under the covers, some system properties correspond to certain standard HTTP headers. The Azure Storage client library for .NET maintains these properties for you.

  • User-defined metadata: User-defined metadata consists of one or more name-value pairs that you specify for a Blob storage resource. You can use metadata to store additional values with the resource. Metadata values are for your own purposes only, and don't affect how the resource behaves.

    Metadata name/value pairs are valid HTTP headers and should adhere to all restrictions governing HTTP headers. For more information about metadata naming requirements, see Metadata names.

Note

Blob index tags also provide the ability to store arbitrary user-defined key/value attributes alongside an Azure Blob storage resource. While similar to metadata, only blob index tags are automatically indexed and made searchable by the native blob service. Metadata cannot be indexed and queried unless you utilize a separate service such as Azure Search.

To learn more about this feature, see Manage and find data on Azure Blob storage with blob index.

Set and retrieve properties

The following code example sets the ContentType and ContentLanguage system properties on a blob.

To set properties on a blob, call SetHttpHeaders or SetHttpHeadersAsync. Any properties not explicitly set are cleared. The following code example first gets the existing properties on the blob, then uses them to populate the headers that aren't being updated.

public static async Task SetBlobPropertiesAsync(BlobClient blob)
{
    Console.WriteLine("Setting blob properties...");

    try
    {
        // Get the existing properties
        BlobProperties properties = await blob.GetPropertiesAsync();

        BlobHttpHeaders headers = new BlobHttpHeaders
        {
            // Set the MIME ContentType every time the properties 
            // are updated or the field will be cleared
            ContentType = "text/plain",
            ContentLanguage = "en-us",

            // Populate remaining headers with 
            // the pre-existing properties
            CacheControl = properties.CacheControl,
            ContentDisposition = properties.ContentDisposition,
            ContentEncoding = properties.ContentEncoding,
            ContentHash = properties.ContentHash
        };

        // Set the blob's properties.
        await blob.SetHttpHeadersAsync(headers);
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

The following code example gets a blob's system properties and displays some of the values.

private static async Task GetBlobPropertiesAsync(BlobClient blob)
{
    try
    {
        // Get the blob properties
        BlobProperties properties = await blob.GetPropertiesAsync();

        // Display some of the blob's property values
        Console.WriteLine($" ContentLanguage: {properties.ContentLanguage}");
        Console.WriteLine($" ContentType: {properties.ContentType}");
        Console.WriteLine($" CreatedOn: {properties.CreatedOn}");
        Console.WriteLine($" LastModified: {properties.LastModified}");
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

Set and retrieve metadata

You can specify metadata as one or more name-value pairs on a blob or container resource. To set metadata, add name-value pairs to the Metadata collection on the resource. Then, call one of the following methods to write the values:

The following code example sets metadata on a blob. One value is set using the collection's Add method. The other value is set using implicit key/value syntax.

public static async Task AddBlobMetadataAsync(BlobClient blob)
{
    Console.WriteLine("Adding blob metadata...");

    try
    {
        IDictionary<string, string> metadata =
           new Dictionary<string, string>();

        // Add metadata to the dictionary by calling the Add method
        metadata.Add("docType", "textDocuments");

        // Add metadata to the dictionary by using key/value syntax
        metadata["category"] = "guidance";

        // Set the blob's metadata.
        await blob.SetMetadataAsync(metadata);
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

The following code example reads the metadata on a blob.

To retrieve metadata, call the GetProperties or GetPropertiesAsync method on your blob or container to populate the Metadata collection, then read the values, as shown in the example below. The GetProperties method retrieves blob properties and metadata by calling both the Get Blob Properties operation and the Get Blob Metadata operation.

public static async Task ReadBlobMetadataAsync(BlobClient blob)
{
    try
    {
        // Get the blob's properties and metadata.
        BlobProperties properties = await blob.GetPropertiesAsync();

        Console.WriteLine("Blob metadata:");

        // Enumerate the blob's metadata.
        foreach (var metadataItem in properties.Metadata)
        {
            Console.WriteLine($"\tKey: {metadataItem.Key}");
            Console.WriteLine($"\tValue: {metadataItem.Value}");
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

Resources

To learn more about how to manage system properties and user-defined metadata 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 managing system properties and user-defined metadata use the following REST API operations:

Client library resources

  • 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.