This topic describes how to use the OSS C# SDK to determine whether a file exists.
Prerequisites
The sample code in this topic uses the China (Hangzhou) region (
cn-hangzhou) as an example. By default, the public endpoint is used. 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.The example in this topic uses environment variables to read access credentials. For more information about how to configure access credentials, see [Configure access credentials for .NET 2.0].
Downloading a file locally requires the
oss:GetObjectpermission. For more information, see Grant a custom access policy to a RAM user.
Sample code
You can use the following code to determine whether a file exists.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the 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 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 Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name"; // Required. The name of the destination bucket.
var key = "your object name"; // Required. The name of the destination object. The format is folder/objectName.
// Load the default configurations of the OSS SDK. These configurations automatically read credential information such as an AccessKey from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in 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 based on the configuration information.
using var client = new OSS.Client(cfg);
// Call the IsObjectExistAsync method to determine whether the destination object exists.
var result = await client.IsObjectExistAsync(bucket, key);
// Print a message indicating that the operation is complete.
Console.WriteLine("IsObjectExist done");
// Print the check result. true indicates that the object exists. false indicates that the object does not exist.
Console.WriteLine($"result: {result}");References
For the complete sample code, see IsObjectExist.cs.