对于较新版本的Microsoft.WindowsAzure.Storage,请使用正确的CloudBlobClient.ListContainersSegmentedAsync
方法变体。以下是用法示例:
private static async Task<IEnumerable<CloudBlobContainer>> ListContainersAsync(CloudBlobClient cloudBlobClient)
{
BlobContinuationToken continuationToken = null;
var containers = new List<CloudBlobContainer>();
do
{
ContainerResultSegment response = await cloudBlobClient.ListContainersSegmentedAsync(continuationToken);
continuationToken = response.ContinuationToken;
containers.AddRange(response.Results);
} while (continuationToken != null);
return containers;
}
使用上述方法的步骤如下:
string connectionString = "<your connection string>";
CloudStorageAccount.TryParse(connectionString, out CloudStorageAccount storageAccount);
if (storageAccount == null)
{
Console.WriteLine("Connection string did not work");
}
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
var containers = await ListContainersAsync(cloudBlobClient);
或者,您可以按照以下方式创建扩展方法:
public static class CloudBlobClientExtension
{
public static async Task<IEnumerable<CloudBlobContainer>> ListContainersAsync(this CloudBlobClient cloudBlobClient)
{
BlobContinuationToken continuationToken = null;
var containers = new List<CloudBlobContainer>();
do
{
ContainerResultSegment response = await cloudBlobClient.ListContainersSegmentedAsync(continuationToken);
continuationToken = response.ContinuationToken;
containers.AddRange(response.Results);
} while (continuationToken != null);
return containers;
}
}
以上扩展方法的使用方法如下:
string connectionString = "<your connection string>";
CloudStorageAccount.TryParse(connectionString, out CloudStorageAccount storageAccount);
if (storageAccount == null)
{
Console.WriteLine("Connection string did not work");
}
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
IEnumerable<CloudBlobContainer> containers = await cloudBlobClient.ListContainersAsync();
如需更多详细信息,请参考MSDN和Balkan's Blog
对于早期的Azure Storage版本,请使用CloudBlobClient.ListContainers
方法。示例用法如下:
string connectionString = "<your connection string>";
CloudStorageAccount.TryParse(connectionString, out CloudStorageAccount storageAccount);
if (storageAccount == null)
{
Console.WriteLine("Connection string did not work");
}
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
var containers = cloudBlobClient.ListContainers();