问题描述
我使用WindowsAzure.Storage.Blob找到了一些答案,但是此软件包已弃用。
所以我需要使用.net core从Azure获取Blob存储中的容器列表。
解决方法
添加“ Azure.Storage.Blobs” NuGet程序包。
使用BlobServiceClient类
string connectionString = "";
BlobServiceClient client = new BlobServiceClient(connectionString);
使用GetBlobContainers或GetBlobContainersAsync检索容器:
//-------------------------------------------------
// List containers
//-------------------------------------------------
async static Task ListContainers(BlobServiceClient blobServiceClient,string prefix,int? segmentSize)
{
string continuationToken = string.Empty;
try
{
do
{
// Call the listing operation and enumerate the result segment.
// When the continuation token is empty,the last segment has been returned
// and execution can exit the loop.
var resultSegment =
blobServiceClient.GetBlobContainersAsync(BlobContainerTraits.Metadata,prefix,default)
.AsPages(continuationToken,segmentSize);
await foreach (Azure.Page<BlobContainerItem> containerPage in resultSegment)
{
foreach (BlobContainerItem containerItem in containerPage.Values)
{
Console.WriteLine("Container name: {0}",containerItem.Name);
}
// Get the continuation token and loop until it is empty.
continuationToken = containerPage.ContinuationToken;
Console.WriteLine();
}
} while (continuationToken != string.Empty);
}
catch (RequestFailedException e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
如果要搜索以某些前缀开头的容器,则前缀参数是可选的。
代码来自documentation: