10

I need to compare from a list that I have to the files in a blob storage of azure, the only part I need is a way to get a list of the files in that blob.

For example

blob azureImages
files:
name
something.jpg
asd.jpg
iwda.jpg
my list:
name
something.jpg
asd.jpg

When I compare the files from the blob with my list, I'd like to delete the files that have no match in my list.

1 Answer 1

22

You can get a list of blobs in a container with CloudBlobContainer.ListBlobs() or inside a directory with CloudBlobDirectory.ListBlobs()

CloudBlobClient blobClient = new CloudBlobClient(blobEndpoint, new StorageCredentialsAccountAndKey(accountName, accountKey));

//Get a reference to the container.
CloudBlobContainer container = blobClient.GetContainerReference("container");

//List blobs and directories in this container
var blobs = container.ListBlobs();

foreach (var blobItem in blobs)
{
    Console.WriteLine(blobItem.Uri);
}

You'll need to parse the file name from blobItem.Uri, but then you can use LINQ's Except() method to find the difference:

public string FindFilesToDelete(IEnumerable<string> fromAzure, IEnumerable<string> yourList)
{
     return fromAzure.Except(yourList);
}

which will return everything in the fromAzure list that isn't in yourList.

And lastly you can delete the blobs with this example

2
  • 2
    I have this structure container/folder1/folder2/folder3/myfile.txt. Container.ListBlobs return upto folder1 only. Is there a way to get all files, say in folder3?
    – Allen King
    Dec 29, 2014 at 3:32
  • @AllenKing after GetContainerReference("container"), do var blobs = blobContainer.GetDirectoryReference("folder1/folder2/folder3").ListBlobs(); That will return all blobs in folder3.
    – ScubaSteve
    Apr 23, 2020 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.