使用 .NET 管理 blob 属性和元数据Manage blob properties and metadata with .NET

除 Blob 包含的数据外,它们还支持系统属性和用户定义的元数据。In addition to the data they contain, blobs support system properties and user-defined metadata. 本文介绍如何使用用于 .NET 的 Azure 存储客户端库管理系统属性和用户定义元数据。This article shows how to manage system properties and user-defined metadata with the Azure Storage client library for .NET.

关于属性和元数据About properties and metadata

  • 系统属性:系统属性存在于每个 Blob 存储资源上。System properties: System properties exist on each Blob storage resource. 其中一些属性是可以读取或设置的,而另一些属性是只读的。Some of them can be read or set, while others are read-only. 事实上,有些系统属性与某些标准 HTTP 标头对应。Under the covers, some system properties correspond to certain standard HTTP headers. 用于 .NET 的 Azure 存储客户端库将维护这些属性。The Azure Storage client library for .NET maintains these properties for you.

  • 用户定义的元数据:用户定义元数据包含一个或多个你为 Blob 存储资源指定的名称/值对对。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.

设置和检索属性Set and retrieve properties

以下代码示例设置 blob 的 ContentTypeContentLanguage 系统属性。The following code example sets the ContentType and ContentLanguage system properties on a blob.

若要在 Blob 上设置属性,请调用 SetHttpHeadersSetHttpHeadersAsyncTo set properties on a blob, call SetHttpHeaders or SetHttpHeadersAsync. 清除未显式设置的任何属性。Any properties not explicitly set are cleared. 下面的代码示例首先获取 Blob 上的现有属性,然后使用它们填充未更新的标头。The following code example first gets the existing properties on the blob, then uses them to populate the headers that are not 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();
    }
}

以下代码示例获取 blob 的系统属性并显示一些值。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

可将元数据指定为 Blob 或容器资源上的一个或多个名称/值对。You can specify metadata as one or more name-value pairs on a blob or container resource. 若要设置元数据,请将名称/值对添加到资源上的 Metadata 集合。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:

元数据名称/值对是有效的 HTTP 标头,因此应当遵循所有控制 HTTP 标头的限制。Metadata name/value pairs are valid HTTP headers and should adhere to all restrictions governing HTTP headers. 元数据名称必须是有效的 HTTP 标头名称和有效的 C# 标识符,只能包含 ASCII 字符,并且应当区分大小写。Metadata names must be valid HTTP header names and valid C# identifiers, may contain only ASCII characters, and should be treated as case-insensitive. 包含非 ASCII 字符的 Base64 编码URL 编码的元数据值。Base64-encode or URL-encode metadata values containing non-ASCII characters.

元数据的名称必须符合 C# 标识符命名约定。The name of your metadata must conform to the naming conventions for C# identifiers. 元数据名称保留创建时使用的大小写,但在设置或读取时不区分大小写。Metadata names maintain the case used when they were created, but are case-insensitive when set or read. 如果为资源提交了两个或更多个名称相同的元数据标头,Azure Blob 存储会返回 HTTP 错误代码“400 (请求错误)”。If two or more metadata headers using the same name are submitted for a resource, Azure Blob storage returns HTTP error code 400 (Bad Request).

以下代码示例在 blob 上设置元数据。The following code example sets metadata on a blob. 一个值是使用集合的 Add 方法设置的。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();
    }
}

以下代码示例在 Blob 上读取元数据。The following code example reads the metadata on a blob.

要检索元数据,请对 blob 或容器调用 GetPropertiesGetPropertiesAsync 方法以填充 Metadata 集合,然后读取值,如下面的示例所示。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.

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

使用 .NET 进行开发的资源Resources for development with .NET

下面的链接为使用适用于 .NET 的 Azure 存储客户端库的开发人员提供了有用的资源。The links below provide useful resources for developers using the Azure Storage client library for .NET.

Azure 存储通用 APIAzure Storage common APIs

Blob 存储 APIBlob storage APIs

.NET 工具.NET tools

请参阅See also