Skip to content

Instantly share code, notes, and snippets.

@Dillie-O
Last active August 29, 2015 14:03
Show Gist options
  • Save Dillie-O/f5286e77eb37b95281bd to your computer and use it in GitHub Desktop.
Save Dillie-O/f5286e77eb37b95281bd to your computer and use it in GitHub Desktop.
Delete old files in Azure container
Console.WriteLine("Starting Clean Containers WebJob...");
try
{
var removeThreshold = int.Parse(ConfigurationManager.AppSettings["RemoveThresholdDays"]);
var storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
var dataContainerName = CloudConfigurationManager.GetSetting("StorageContainerDataName");
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var dataContainer = blobClient.GetContainerReference(dataContainerName);
Console.WriteLine("Day threshold to remove records: {0}", removeThreshold);
// Retrieve all data items greater than a month old and delete them.
Console.WriteLine("Retrieving old data files...");
var oldData = dataContainer.ListBlobs()
.OfType<CloudBlob>()
.Where(b => b.Properties.LastModifiedUtc < DateTime.Now.AddDays((removeThreshold * -1)));
var dataBlobs = oldData as IList<CloudBlob> ?? oldData.ToArray();
Console.WriteLine("Data records retrieved: {0}.", dataBlobs.Count());
Console.WriteLine("Removing old data files...");
foreach (var dataBlob in dataBlobs.Select(log => logContainer.GetBlobReference(log.Uri.ToString())))
{
dataBlob.DeleteIfExists();
}
Console.WriteLine("Removing old data complete.");
}
catch (Exception ex)
{
Console.WriteLine("Error cleaning container files: {0}", ex);
}
Console.WriteLine("Clean Containers WebJob complete.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment