Este tópico descreve como listar todos os buckets da sua conta em ordem alfabética.
Observações
Os exemplos deste tópico usam o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).
Para listar buckets, é necessária a permissão
oss:ListBuckets. Para mais detalhes, consulte Conceder uma política personalizada.
Código de exemplo
O código a seguir mostra como listar todos os buckets da sua conta.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// List all buckets in your account.
try
{
var buckets = client.ListBuckets();
Console.WriteLine("List bucket succeeded");
foreach (var bucket in buckets)
{
Console.WriteLine("Bucket name: {0}, Location: {1}, Owner: {2}", bucket.Name, bucket.Location, bucket.Owner);
}
}
catch (Exception ex)
{
Console.WriteLine("List bucket failed. {0}", ex.Message);
}
Referências
Para acessar o código de exemplo completo de listagem de buckets, consulte o exemplo no GitHub.
Para mais informações sobre a operação de API de listagem de buckets, consulte ListBuckets (GetService).