Kanasi
Kanasi

Reputation: 95

BlobRetentionPolicy() how to use it? I need to set expiry days for my azure blob file

I'm using this package: Azure Storage Blobs of version 12.16.0.

In order to force the file to be automatically removed from the Azure container, I need to work with Life Cycle policy.

I found this class:

var retentionPolicy = new BlobRetentionPolicy(){ Days = 15, Enabled = true };

But I don't know hot to use this with blob class or container class. In which place this class must be used? How to use it? BlobContainerClient or BlobClient classes doesn't have it methods to Set this policy.

I'm waiting to find a method that will allow me to set the given policy from C# code!

Upvotes: 0

Views: 1402

Answers (2)

Adriaan de Beer
Adriaan de Beer

Reputation: 1286

You can manage policies via Microsoft.Azure.Management.Fluent nuget package.

First you must authenticate to obtain an instance of Microsoft.Azure.Management.Fluent.IAzure

After that, you can use this C# fluent code to create the required lifecyle policy and rule(s) as per your needs. Example:

IAzure azure = ... // authenticate
var policy = azure
    .CreatePolicy(resourceGroup, blobStorageAccountName, policyName)
    .WithTimeToLivePolicyRule("AutoDeleteAfterDay", 1, 
       new[] { "myBlobPrefix" })
    .Attach();

await policy
    .CreateAsync(cancellation);

Upvotes: 0

SwethaKandikonda
SwethaKandikonda

Reputation: 8254

Adding to @jdweng comments, you can use Put Blob Rest Api as below

PUT https://myaccount.blob.core.windows.net/mycontainer/myblob

Version 2020-06-12 and later. Specifies the retention-until date to be set on the blob. This is the date until which the blob can be protected from being modified or deleted. Follows RFC1123 format.

where you can set x-ms-immutability-policy-until-date in your Request body to set the retention policy.

Alternatively, you can manually delete blobs by comparing the dates to check if the blob is created 15 days ago or not as below.

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

class Program
{
    public static void Main(string[] args)
    {
        BlobServiceClient blobServiceClient = new BlobServiceClient("<CONNECTION_STRING>");
        
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("container");

        foreach(BlobItem blob in containerClient.GetBlobs())
        {
            BlobClient blobClient = containerClient.GetBlobClient(blob.Name);

            int dateDifference = blobClient.GetProperties().Value.CreatedOn.Date.CompareTo(DateTimeOffset.UtcNow.Date);

            if (dateDifference == 15)
            {
                blobClient.Delete();
                Console.WriteLine($"Deleted {blob.Name} which is created {dateDifference} days ago");
            }
        }
    }
}

For demonstration purposes, I have set date difference as 0.

Results:

enter image description here

Upvotes: 0

Related Questions