Use ListBuckets() to retrieve all buckets in your account. Results are returned in alphabetical order.
Prerequisites
Before you begin, make sure you have:
The
oss:ListBucketspermission. For details, see Attach a custom policy to a RAM userThe
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables set with your access key credentials
Usage notes
The example uses the public endpoint for the China (Hangzhou) region. If you access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For a full list of endpoints, see Regions and endpoints.
The example creates an
OSSClientinstance using an OSS endpoint. For other initialization options — such as a custom domain or Security Token Service (STS) credentials — see Initialization.
List all buckets
The example below initializes an OSSClient with Signature Version V4 and calls ListBuckets(). Each bucket in the response includes its name, location, and owner.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set the endpoint for the region where your buckets are located.
// Example: China (Hangzhou) -> https://oss-cn-hangzhou.aliyuncs.com
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Load credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set the region ID that matches your endpoint.
const string region = "cn-hangzhou";
// Configure the client to use Signature Version V4.
var conf = new ClientConfiguration();
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// List all buckets in the account.
try
{
var buckets = client.ListBuckets();
Console.WriteLine("List bucket succeeded");
foreach (var bucket in buckets)
{
Console.WriteLine("Bucket name: {0}, Location: {1}, Owner: {2}",
bucket.Name, bucket.Location, bucket.Owner);
}
}
catch (Exception ex)
{
Console.WriteLine("List bucket failed. {0}", ex.Message);
}What's next
For the complete sample project, see the GitHub sample.
For the underlying REST API, see ListBuckets (GetService).