Home > database >  How to update an existing Blob in Azure Storage in .NET 6 or in ASP.NET Core
How to update an existing Blob in Azure Storage in .NET 6 or in ASP.NET Core

Time:07-20

I have prepared some C# code to create a container in the Azure Storage and then I am uploading a file into that azure container. The code is below:

var connectionString = _settings.appConfig.StorageConnectionString;
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient("nasir-container");            
await blobContainer.CreateIfNotExistsAsync(); // Create the container.

BlobClient blobClient = blobContainer.GetBlobClient(fileName); // Creating the blob

string fileName = "D:/Workspace/Adappt/MyWordFile.docx";
FileStream uploadFileStream = System.IO.File.OpenRead(fileName);
blobClient.Upload(uploadFileStream);
uploadFileStream.Close();

Now I have updated my MyWordFile.docx with more content. Now I would like to upload this updated file to the same blob storage. How can I do this? I also want to create versioning too so that I can get the file content based on the version.

CodePudding user response:

Now I have updated my MyWordFile.docx with more content. Now I would like to upload this updated file to the same blob storage. How can I do this?

To update a blob, you simply upload the same file (basically use the same code you wrote to upload the file in the first place). Upload operation will overwrite an existing blob.

I also want to create versioning too so that I can get the file content based on the version.

There are two ways you can implement versioning for blobs:

  1. Automatic versioning: If you want Azure Blob Storage service to maintain versions of your blobs, all you need to do is enable versioning on the storage account. Once you enable that, anytime a blob is modified a new version of the blob will be created automatically for you by service. Please see this link to learn more about blob versioning: enter image description here

    • Just click on Disable it will take you to a different page and select enable version and click save

    • Here after uploading the blob when you update the blob it will automatically trigger the creating of versions.

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

    The above code is from the following documentation.

  • Related