Call GetBucketLocation using the OSS SDK for C# 1.0 to retrieve the region where a bucket is located.
Usage notes
The sample code uses the public endpoint for the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For a full list of regions and endpoints, see Regions and Endpoints.
The sample code creates an OSSClient instance using an OSS endpoint. To create an OSSClient instance using a custom domain name or Security Token Service (STS), see Initialization.
To query the region of a bucket, you must have the
oss:GetBucketLocationpermission. For more information, see Grant a custom policy.
Sample code
The following code calls GetBucketLocation and prints the bucket's region. The result.Location property returns a region ID such as cn-hangzhou.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of a region that is supported by OSS. 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 configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "yourBucketName";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Query 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 the API operation that queries the region of a bucket, see GetBucketLocation.