Sharad
Sharad

Reputation: 435

Azure blob storage, how to implement version of any document or files

In Azure blob storage, I would like to store multiple version of same file( file name), I mean how to implement versioning in Azure blob storage.

Upvotes: 0

Views: 2167

Answers (2)

subhankars
subhankars

Reputation: 371

Azure Blob Versioning is Generally Available now. From azure portal Under Data Protection >> Tracking >> Turn on Versioning option is available. This will completely solve your problem. A complete guide with C# code sample is available in the link below on document versioning in Azure Blob Storage. https://subhankarsarkar.com/document-versioning-with-azure-blob-storage/

Code Sample for downloading a file by version

public async Task<byte[]> DownloadBlobAsync(string fileToDownload, string fileVersion)
{
  using (var ms = new MemoryStream())
  {
    var blobClient = BlobContainerClient.GetBlockBlobClient(fileToDownload);
    // WithVersion() is the key piece here
    var blob = blobClient.WithVersion(fileVersion);
    await blob.DownloadToAsync(ms);
    return ms.ToArray();
  }
}

Restore a file to a specific version

public void RestoreFileToSpecificVersion(string storageAccountName, string containerName, string fileName, string sourceVersion)
{
    var blobClient = BlobContainerClient.GetBlockBlobClient(fileName); // this is pointing to the current version
    //versionid={} is the most important piece here
    var sourceBlobUri = new Uri(
    string.Format("https://{0}.blob.core.windows.net/{1}/{2}?versionid={3}",
    storageAccountName, containerName, fileName, sourceVersion));

    // Since it will copy in the same storage account's container, it's a synchronous process
    // Copy Operation will make the specic version as current version
    // See https://learn.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url#request-headers
    blobClient.StartCopyFromUri(sourceBlobUri);
}

Delete a file by it's version

public async Task DeleteSpecificVersion(string fileName, string versionToDelete)
{
   var blobClient = BlobContainerClient.GetBlockBlobClient(fileName).WithVersion(versionToDelete);
   await blobClient.DeleteAsync();
}

Upvotes: 4

Gaurav Mantri
Gaurav Mantri

Reputation: 136306

Versioning in Azure Blob Storage is supported through Snapshot Blob feature where when you create a snapshot of the blob, a read only copy of the blob is created.

You can read more about it here: https://learn.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob.

Upvotes: 2

Related Questions