Creare ed elencare le versioni BLOB in .NET
Il controllo delle versioni BLOB crea automaticamente una versione precedente di un BLOB ogni volta che viene modificata o eliminata. Quando il controllo delle versioni BLOB è abilitato, è possibile ripristinare una versione precedente di un BLOB per recuperare i dati se viene modificato o eliminato erroneamente.
Per la protezione dei dati ottimale, Microsoft consiglia di abilitare l'eliminazione temporanea delle versioni BLOB e BLOB per l'account di archiviazione. Per altre informazioni, vedere Controllo delle versioni BLOB e Eliminazione temporanea per i BLOB.
Modificare un BLOB per attivare una nuova versione
Nell'esempio di codice seguente viene illustrato come attivare la creazione di una nuova versione con la libreria client di Archiviazione di Azure per .NET, versione 12.5.1 o successiva. Prima di eseguire questo esempio, assicurarsi di avere abilitato il controllo delle versioni per l'account di archiviazione.
L'esempio crea un BLOB a blocchi e quindi aggiorna i metadati del BLOB. L'aggiornamento dei metadati del BLOB attiva la creazione di una nuova versione. L'esempio recupera la versione iniziale e la versione corrente e mostra che solo la versione corrente include i metadati.
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);
}
}
Elencare le versioni BLOB
Per elencare le versioni BLOB, specificare il parametro BLOBStates con il campo Versione . Le versioni sono elencate dalle versioni meno recenti a quelle più recenti.
Nell'esempio di codice seguente viene illustrato come elencare le versioni BLOB.
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;
}
}
Copiare una versione del BLOB precedente nel BLOB di base
È possibile eseguire un'operazione di copia per promuovere una versione nel BLOB di base, purché il BLOB di base si trovi in un livello online (ad accesso frequente o sporadico). La versione rimane, ma la destinazione viene sovrascritta con una copia in cui è possibile leggere e scrivere.
Nell'esempio di codice seguente viene illustrato come copiare una versione BLOB nel BLOB di base:
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;
}
Risorse
Per altre informazioni sulla gestione delle versioni BLOB tramite la libreria client di Archiviazione BLOB di Azure per .NET, vedere le risorse seguenti.
Risorse della libreria client
- Documentazione di riferimento sulla libreria client
- Codice sorgente della libreria client
- Pacchetto (NuGet)