A bucket is a container for storing objects. All objects must be stored in a bucket. This topic describes how to retrieve the region, also known as the location, of a bucket.
Notes
This topic uses the public endpoint of the China (Hangzhou) region as an example. If you want to access OSS from other Alibaba Cloud services in the same region, you can use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.
The sample code in this topic demonstrates how to create an OSSClient instance using an OSS domain name. To create an OSSClient instance using other methods, such as a custom domain name or Security Token Service (STS), see Initialization (C# SDK V1).
To retrieve the region of a bucket, you must have the
oss:GetBucketLocationpermission. For more information, see Grant custom access policies to RAM users.
Sample code
The following code shows how to retrieve the region, also known as the location, of a bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of any region that OSS supports. For example, 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");
// Set bucketName to the name of your bucket.
var bucketName = "yourBucketName";
// Specify the region where the bucket is located. For example, set the region to cn-hangzhou for China (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
{
// Get the region of the bucket.
var result = client.GetBucketLocation(bucketName);
Console.WriteLine("Get bucket:{0} Info succeeded ", bucketName);
Console.WriteLine("bucket Location: {0}", result.Location);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}References
For more information about the API operation used to retrieve the region of a bucket, see GetBucketLocation.