Azure Function deletes files older than 30 days - JackyChiou/jackychiou.github.io GitHub Wiki

Azure Function deletes files older than 30 days.

Why need it? https://feedback.azure.com/forums/169385-web-apps/suggestions/39782458-web-app-application-logging-blob-retention

Sample Code:

using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
 
namespace DeleteFilesOlderThanXDays
{
    public static class DeleteFilesOlderThan30Days
    {
        [FunctionName("DeleteFilesOlderThan30Days")]
        public async static Task Run([TimerTrigger("0 30 3 * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
 
            string accountName = "Your Storage Account Name";
            string accountKey = "Your Account Access Key";
 
            log.LogInformation("Storage Account Name: " + accountName);
            var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
            var blobClient = account.CreateCloudBlobClient();
//change it to your container name
            var container = blobClient.GetContainerReference("Your Container Name");
 
            log.LogInformation("Get a list of all blobs in your container");     
            
            BlobResultSegment result = await container.ListBlobsSegmentedAsync(null);
 
            log.LogInformation("Iterate each blob");
 
            int segmentSize = 10000;
 
            BlobContinuationToken continuationToken = null;
            CloudBlob blob;
 
            try
            {
                // Call the listing operation and enumerate the result segment.
                // When the continuation token is null, the last segment has been returned
                // and execution can exit the loop.
                do
                {
                    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(string.Empty,
                        true, BlobListingDetails.Metadata, segmentSize, continuationToken, null, null);
 
                    foreach (var blobItem in resultSegment.Results)
                    {
                        // A flat listing operation returns only blobs, not virtual directories.
                        blob = (CloudBlob)blobItem;
 
                        // Write out some blob properties.
                        log.LogInformation("Blob name: {0} {1}", blob.Name, blob.Properties.LastModified);
 
                        log.LogInformation("Calculate when LastModified is compared to today");
                        TimeSpan? diff = DateTime.Today - blob.Properties.LastModified;
                        // 30 days, you can change it to 90 days and etc.
                        if (diff?.Days > 30)
                        {
                            log.LogInformation("Delete: " + blob.Name);
                            await blob.DeleteAsync();
                        }
                    }
 
                    log.LogInformation($"Foreach completed at: {DateTime.Now}");
 
                    // Get the continuation token and loop until it is null.
                    continuationToken = resultSegment.ContinuationToken;
 
                } while (continuationToken != null);
            }
            catch (StorageException e)
            {
                log.LogInformation(e.Message);
            }
 
            log.LogInformation($"C# Timer trigger function completed at: {DateTime.Now}");
        }
    }
}

Change “Your Storage Account Name”, “Your Account Access Key”, “Your Container Name”, and Days.

Build and publish it to your Function App.

For more information: Create a function in Azure that is triggered by a timer https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-scheduled-function

Timer trigger for Azure Functions https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=csharp