List objects (OSS SDK for C# V2)
This topic describes how to list all objects, a specified number of objects, or objects with a specified prefix in a bucket that has versioning enabled.
Prerequisites
-
The sample code in this topic uses the China (Hangzhou) region as an example. The region ID is
cn-hangzhou. The public endpoint is used by default. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the mappings between OSS regions and endpoints, see OSS regions and endpoints. -
To list objects, you must have the
oss:ListObjectVersionspermission. For more information, see Grant custom permissions to a RAM user.
Sample code
The following code provides an example of how to list the version information of objects in a specified bucket.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name"; // Required. The name of the bucket.
var key = "your object name Prefix"; // Required. The prefix of the destination object in the bucket.
// 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 for 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);
// Create a ListObjectVersions request and set the bucket name.
var request = new OSS.Models.ListObjectVersionsRequest
{
Bucket = bucket,
Prefix = key, // List only object versions that start with the specified prefix.
MaxKeys = 100 // The maximum number of objects to return for each request.
};
// Create a paginator instance.
var paginator = client.ListObjectVersionsPaginator(request);
// Use a foreach loop to traverse all pages.
foreach (var page in paginator.IterPage())
{
if (page.Versions != null)
{
foreach (var version in page.Versions)
{
Console.WriteLine($"Object Key: {version.Key}, Version ID: {version.VersionId}");
}
}
}