This topic describes how to determine whether a specified bucket exists using the C# SDK V2.
Notes
The sample code in this topic uses the China (Hangzhou) region ID,
cn-hangzhou, as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about the mappings between OSS regions and endpoints, see OSS regions and endpoints.To determine whether a bucket exists, you must have the
oss:GetBucketAclpermission. For more information, see Grant custom permissions to a RAM user.
Sample code
You can use the following code to determine whether a bucket exists.
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). References
For the complete sample code, see is_bucket_exist.cs.