Este tópico descreve como verificar se um bucket específico existe usando o C# SDK V2.
Observações
O código de exemplo neste tópico usa o ID de região China (Hangzhou),
cn-hangzhou, como exemplo. Por padrão, o endpoint público é usado. Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use o endpoint interno. Para mais informações sobre o mapeamento entre regiões e endpoints do OSS, consulte OSS regions and endpoints.Para verificar se um bucket existe, você precisa ter a permissão
oss:GetBucketAcl. Para mais informações, consulte Grant custom permissions to a RAM user.
Código de exemplo
Use o código a seguir para verificar se um bucket existe.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for 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 located in the China (Hangzhou) region, set the region to cn-hangzhou.
var bucket = "your bucket name"; // Required. Specify the name of the destination bucket.
var endpoint = null as string; // Optional. Specify the endpoint for accessing OSS. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
// 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 IsBucketExistAsync method to determine whether the destination bucket exists.
var result = await client.IsBucketExistAsync(bucket);
// Print the result.
Console.WriteLine("IsBucketExist done"); // Prompt that the operation is complete.
Console.WriteLine($"result: {result}"); // Print whether the bucket exists (True for exists, False for not exists).
Referências
Para acessar o código de exemplo completo, consulte is_bucket_exist.cs.