A bucket is a container used to store objects in Object Storage Service (OSS). This topic describes how to determine whether a bucket exists.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.
To determine whether a bucket exists, you must have the
oss:GetBucketAclpermission. For more information, see Attach a custom policy to a RAM user.
Sample code
The following code shows how to check whether a specified bucket exists:
using System;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace Samples
{
public class Program
{
public static void Main(string[] args)
{
// Set yourEndpoint to 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 this 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");
// Set the bucket name. For example, examplebucket.
var bucketName = "examplebucket";
// Set 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);
try
{
var exist = client.DoesBucketExist(bucketName);
Console.WriteLine("Check object Exist succeeded");
Console.WriteLine("exist ? {0}", exist);
}
catch (Exception ex)
{
Console.WriteLine("Check object Exist failed. {0}", ex.Message);
}
}
}
}References
For the complete sample code, see the GitHub sample.