Este tópico descreve como usar o OSS SDK for C# para listar todos os objetos em um bucket especificado.
Precauções
O código de exemplo deste tópico usa a região China (Hangzhou) (
cn-hangzhou) como referência. Por padrão, o sistema usa o endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.Este tópico apresenta um exemplo de leitura de credenciais de acesso em variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Para listar objetos, você precisa da permissão
oss:ListObjects. Para obter mais informações, consulte Conceder permissões personalizadas a um usuário RAM.
Código de exemplo
Use o código a seguir para listar todos os objetos no bucket especificado.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. 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.
var endpoint = null as string; // Optional. Specify the domain name used to access the OSS service. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name"; // Required. The name of the destination bucket.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overwrites the default endpoint.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg);
// Call the ListObjectsV2Paginator method to obtain all objects in the destination bucket.
var paginator = client.ListObjectsV2Paginator(new OSS.Models.ListObjectsV2Request()
{
Bucket = bucket
});
// Print the information of all objects in the bucket.
Console.WriteLine("Objects:");
await foreach (var page in paginator.IterPageAsync()) // Asynchronously traverse each page of results.
{
// Traverse each object on the current page.
foreach (var content in page.Contents ?? [])
{
// Print the object information: key, size (in bytes), and last modified time.
Console.WriteLine($"Object:{content.Key}, {content.Size}, {content.LastModified}");
}
}
Referências
Para obter o código de exemplo completo, consulte ListObjects.cs.