Azure Storage SDK for Blob storage - How to set the expiration date of a blob relative to the current time

207 Views Asked by At

I can see from the Azure Storage REST API documentation, that it is possible to set the expiration date of a blob at the time it is created.

Is it possible to set a newly created blob's expiration date via the Azure Blob Storage client library for .NET?

If someone has an example or link to more information, it would be appreciated.

1

There are 1 best solutions below

2
Venkatesan On

Is it possible to set a newly created blob's expiration date via the Azure Blob Storage client library for .NET?

You can use the below code to set the expiration date of a blob relative to the current time with the request method using C#.

Code:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://<storage account name>.blob.core.windows.net";
        string containerName = "test";
        string blobName = "demo.png";
        string SAStoken = "sp=w&st=2023-11-14T07:16:20Z&se=2023-11-14T15:16:20Z&spr=https&sv=2022-11-02&sr=b&sig==xxxxx"; //write permission
        DateTime dt = DateTime.UtcNow;

        using (HttpClient httpClient = new HttpClient())
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, new Uri($"{url}/{containerName}/{blobName}?comp=expiry&{SAStoken}"));
            request.Headers.Add("x-ms-version", "2020-02-10");
            request.Headers.Add("x-ms-expiry-time", "60000"); //one minute
            request.Headers.Add("x-ms-expiry-option", "RelativeTonow");
            request.Headers.Add("x-ms-date", dt.ToString("R"));
            HttpResponseMessage response = await httpClient.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Expiry Time added to the blob successfully");
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
            }
        }
    }
}

The above code adds an expiry time as a sample of (one minute) to a blob in Azure Blob Storage using a Shared Access Signature (SAS) token. The code creates an HTTP PUT request to the blob URL with the expiry time specified in the request headers.

Output:

Expiry Time added to the blob successfully

enter image description here

The above code operation is allowed only on hierarchical namespace enabled storage accounts.

Reference: Set Blob Expiry (REST API) - Azure Storage | Microsoft Learn