Aracılığıyla paylaş


.NET'te blob sürümlerini oluşturma ve listeleme

Blob sürümü oluşturma, her değiştirildiğinde veya silindiğinde blobun önceki bir sürümünü otomatik olarak oluşturur. Blob sürümü oluşturma etkinleştirildiğinde, yanlışlıkla değiştirildiğinde veya silindiğinde verilerinizi kurtarmak için blobun önceki bir sürümünü geri yükleyebilirsiniz.

En iyi veri koruması için Microsoft, depolama hesabınız için hem blob sürümü oluşturmanın hem de blob geçici silmenin etkinleştirilmesini önerir. Daha fazla bilgi için bkz . Blob sürümü oluşturma ve Bloblar için geçici silme.

Blobu değiştirerek yeni bir sürümü tetikleme

Aşağıdaki kod örneği. .NET, sürüm 12.5.1 veya üzeri için Azure Depolama istemci kitaplığı ile yeni bir sürümün oluşturulmasını tetikleme işlemi gösterilmektedir. Bu örneği çalıştırmadan önce depolama hesabınız için sürüm oluşturma özelliğini etkinleştirdiğinizden emin olun.

Örnek bir blok blobu oluşturur ve ardından blob'un meta verilerini güncelleştirir. Blobun meta verilerinin güncelleştirilmesi yeni bir sürümün oluşturulmasını tetikler. Örnek, ilk sürümü ve geçerli sürümü alır ve meta verileri yalnızca geçerli sürümün içerdiğini gösterir.

public static async Task UpdateVersionedBlobMetadata(BlobContainerClient blobContainerClient, 
                                                     string blobName)
{
    try
    {
        // Create the container.
        await blobContainerClient.CreateIfNotExistsAsync();

        // Upload a block blob.
        BlockBlobClient blockBlobClient = blobContainerClient.GetBlockBlobClient(blobName);

        string blobContents = string.Format("Block blob created at {0}.", DateTime.Now);
        byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);

        string initalVersionId;
        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            Response<BlobContentInfo> uploadResponse = 
                await blockBlobClient.UploadAsync(stream, null, default);

            // Get the version ID for the current version.
            initalVersionId = uploadResponse.Value.VersionId;
        }

        // Update the blob's metadata to trigger the creation of a new version.
        Dictionary<string, string> metadata = new Dictionary<string, string>
        {
            { "key", "value" },
            { "key1", "value1" }
        };

        Response<BlobInfo> metadataResponse = 
            await blockBlobClient.SetMetadataAsync(metadata);

        // Get the version ID for the new current version.
        string newVersionId = metadataResponse.Value.VersionId;

        // Request metadata on the previous version.
        BlockBlobClient initalVersionBlob = blockBlobClient.WithVersion(initalVersionId);
        Response<BlobProperties> propertiesResponse = await initalVersionBlob.GetPropertiesAsync();
        PrintMetadata(propertiesResponse);

        // Request metadata on the current version.
        BlockBlobClient newVersionBlob = blockBlobClient.WithVersion(newVersionId);
        Response<BlobProperties> newPropertiesResponse = await newVersionBlob.GetPropertiesAsync();
        PrintMetadata(newPropertiesResponse);
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

static void PrintMetadata(Response<BlobProperties> propertiesResponse)
{
    if (propertiesResponse.Value.Metadata.Count > 0)
    {
        Console.WriteLine("Metadata values for version {0}:", propertiesResponse.Value.VersionId);
        foreach (var item in propertiesResponse.Value.Metadata)
        {
            Console.WriteLine("Key:{0}  Value:{1}", item.Key, item.Value);
        }
    }
    else
    {
        Console.WriteLine("Version {0} has no metadata.", propertiesResponse.Value.VersionId);
    }
}

Blob sürümlerini listeleme

Blob sürümlerini listelemek için, BlobStates parametresini Version alanıyla belirtin. Sürümler en eskisinden en yenisine listelenir.

Aşağıdaki kod örneğinde blob sürümlerini listeleme gösterilmektedir.

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

Önceki bir blob sürümünü temel blob üzerinden kopyalama

Temel blob çevrimiçi katmanda (sık erişimli veya seyrek erişimli) olduğu sürece bir sürümü temel blobu üzerinden yükseltmek için kopyalama işlemi gerçekleştirebilirsiniz. Sürüm kalır, ancak okunabilen ve yazılabilir bir kopyayla hedefinin üzerine yazılır.

Aşağıdaki kod örneği, bir blob sürümünün temel blob üzerinden nasıl kopyalanmasını gösterir:

public static async Task<BlockBlobClient> CopyVersionOverBaseBlobAsync(
    BlockBlobClient client,
    string versionTimestamp)
{
    // Instantiate BlobClient with identical URI and add version timestamp
    BlockBlobClient versionClient = client.WithVersion(versionTimestamp);

    // Restore the specified version by copying it over the base blob
    await client.SyncUploadFromUriAsync(versionClient.Uri);

    // Return the client object after the copy operation
    return client;
}

Kaynaklar

.NET için Azure Blob Depolama istemci kitaplığını kullanarak blob sürümlerini yönetme hakkında daha fazla bilgi edinmek için aşağıdaki kaynaklara bakın.

İstemci kitaplığı kaynakları

Ayrıca bkz.