有没有一种方法可以从Azure Blob中获取所有文件?

10
我需要将我拥有的列表与Azure的Blob存储中的文件进行比较,唯一需要的部分是获取该Blob中文件的列表。例如:
blob azureImages
files:
name
something.jpg
asd.jpg
iwda.jpg
my list:
name
something.jpg
asd.jpg

当我将Blob的文件与我的列表进行比较时,我想删除在列表中没有匹配项的文件。

1个回答

22
您可以使用CloudBlobContainer.ListBlobs()获取容器中的Blob列表,或者使用CloudBlobDirectory.ListBlobs()获取目录内的Blob列表。请注意保留HTML标签。
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);
}

你需要从blobItem.Uri中解析出文件名,然后可以使用LINQ的Except()方法找到差异:
public string FindFilesToDelete(IEnumerable<string> fromAzure, IEnumerable<string> yourList)
{
     return fromAzure.Except(yourList);
}

这段代码将返回fromAzure列表中不在yourList中的所有内容。
最后,您可以使用此示例删除blob。

2
我有这个结构 container/folder1/folder2/folder3/myfile.txt。Container.ListBlobs 只返回到 folder1。有没有办法获取所有文件,比如在 folder3 中? - Allen King
@AllenKing 在 GetContainerReference("container") 后,执行 var blobs = blobContainer.GetDirectoryReference("folder1/folder2/folder3").ListBlobs(); 这将返回 folder3 中的所有 blob。 - ScubaSteve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接