Share via


使用 .NET 管理容器屬性和中繼資料

除了包含的資料之外,Blob 容器還支援系統屬性和使用者定義的中繼資料。 此文章說明如何使用適用於 .NET 的 Azure 儲存體用戶端程式庫,來管理系統屬性和使用者定義的中繼資料。

必要條件

關於屬性和中繼資料

  • 系統屬性:系統屬性存在於每個 Blob 儲存體資源上。 其中一些可以讀取或設定,另一些則是唯讀的。 實際上,某些系統屬性會對應至特定標準 HTTP 標頭。 適用於 .NET 的 Azure 儲存體用戶端程式庫會為您維護這些屬性。

  • 使用者定義的中繼資料:使用者定義的中繼資料是由您為 Blob 儲存體資源所指定一或多個成對的名稱和數值所組成。 您可以使用中繼資料來儲存資源的額外值。 中繼資料值僅供您自己使用,並不會影響資源的運作方式。

    中繼資料名稱/值組是有效的 HTTP 標頭,所以應該遵守控管 HTTP 標頭的所有限制。 如需中繼資料命名需求的詳細資訊,請參閱中繼資料名稱

擷取容器屬性

若要擷取容器屬性,請呼叫下列其中一種方法:

下列程式碼範例會擷取容器的系統屬性,並將部分屬性值寫入主控台視窗:

private static async Task ReadContainerPropertiesAsync(BlobContainerClient container)
{
    try
    {
        // Fetch some container properties and write out their values.
        var properties = await container.GetPropertiesAsync();
        Console.WriteLine($"Properties for container {container.Uri}");
        Console.WriteLine($"Public access level: {properties.Value.PublicAccess}");
        Console.WriteLine($"Last modified time in UTC: {properties.Value.LastModified}");
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

設定及擷取中繼資料

您可以將中繼資料指定為 blob 或容器資源上的一個或多個成對的名稱和數值。 若要設定中繼資料,請將名稱值組新增至 IDictionary 物件,然後呼叫下列其中一種方法來寫入值:

下列程式碼範例會在容器上設定中繼資料。

public static async Task AddContainerMetadataAsync(BlobContainerClient container)
{
    try
    {
        IDictionary<string, string> metadata =
           new Dictionary<string, string>();

        // Add some metadata to the container.
        metadata.Add("docType", "textDocuments");
        metadata.Add("category", "guidance");

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

若要擷取中繼資料,請呼叫下列其中一種方法:

接著讀取值,如下列範例所示。

public static async Task ReadContainerMetadataAsync(BlobContainerClient container)
{
    try
    {
        var properties = await container.GetPropertiesAsync();

        // Enumerate the container's metadata.
        Console.WriteLine("Container metadata:");
        foreach (var metadataItem in properties.Value.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 的 Azure Blob 儲存起用戶端程式庫來設定和擷取容器屬性和中繼資料,請參閱下列資源。

REST API 操作

適用於 .NET 的 Azure SDK 包含建置在 Azure REST API 之上的程式庫,可讓您透過熟悉的 .NET 範例與 REST API 作業進行互動。 用來設定與擷取屬性和中繼資料的用戶端程式庫方法會使用下列 REST API 作業:

GetPropertiesGetPropertiesAsync 方法會藉由呼叫取得 Blob 屬性作業和取得 Blob 中繼資料作業來擷取容器屬性和中繼資料。

用戶端程式庫資源