Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Deleting all files (blobs) of an azure container on criteria of file modified date

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 5.00k
    Comment on it

    In my last project I came across a requirement where I had to delete all the blobs from a container using a criteria for modified date with azure web job.


    The criteria for deleting the files were to delete the files whose last modified date time was less than 12 hrs from current utc. I tried different approaches for this purpose and here is the best solution I found for it.


    public void DeleteAllFilesFromTempContainer()
            {
                StorageCredentialsAccountAndKey creds = new StorageCredentialsAccountAndKey(BlobAccountName, BlobAccountKey);
                CloudStorageAccount account = new CloudStorageAccount(creds, false);
                CloudBlobClient blobStorage = new CloudBlobClient(BlobBaseUri, creds);
                CloudBlobContainer container = blobStorage.GetContainerReference(ContainerName); 
    
                //List blobs and directories in this container
                var blobs = container.ListBlobs();
    
        if (blobs == null || blobs.Count() == 0)
                    return;
    
                foreach (IListBlobItem blob in blobs)
                {
                    CloudBlob cloudBlob = container.GetBlobReference(blob.Uri.ToString());
                    cloudBlob.FetchAttributes();
                    if (cloudBlob.Properties.LastModifiedUtc < (DateTime.UtcNow.AddHours(globalServiceManager-12))) //Condition to check whether modified date is less than 12hrs from utc now.
                        cloudBlob.DeleteIfExists();
                }
            }
    

    Here in above method, I am first getting the bloblist using container.ListBlobs() method and after that I am running a foreach loop for all the found blobs in the container. After that I am fetching the attributes of each blob and if the LastModifiedUtc property of blob satisfies the criteria then I am deleting the blob.


    I hope this will help you in similar sort of requirement. Happy coding :)

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: