Upload files (C# SDK V2)

Updated at:

Use C# SDK V2 to upload objects to a versioning-enabled bucket through simple upload or append upload.

Precautions

The sample code uses cn-hangzhou as the region ID and the public endpoint for the China (Hangzhou) region. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about supported regions and endpoints, see OSS regions and endpoints.

Permissions

By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Uploads an object.

oss:PutObjectTagging

Required if you specify object tags by using the x-oss-tagging header when you upload an object.

kms:GenerateDataKey

Required if the X-Oss-Server-Side-Encryption: KMS header is set to KMS when you upload an object.

kms:Decrypt

Examples

Simple upload

Note
  • In a versioning-enabled bucket, OSS automatically generates a unique version ID for each newly uploaded object and returns the version ID in the x-oss-version-id response header.

  • In a bucket for which versioning is suspended, the version ID of a newly uploaded object is "null". If you upload an object that has the same name as an existing object, the newly uploaded object overwrites the existing object. OSS ensures that only one version of an object has a version ID of "null".

The following code shows how to perform a simple upload.

using System.Text; // Import the System.Text namespace to process character encodings, such as UTF-8 encoded strings.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-hangzhou"; // Required. Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
var bucket = "your bucket name";  // Required. Specify the name of the destination bucket.
var endpoint = null as string;  // Optional. Specify the domain name used to access OSS. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var key = "your object key"; // Required. Specify the name of the object to be uploaded. Format: folder/objectName.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as AccessKeys, 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 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 using the configuration information.
using var client = new OSS.Client(cfg);

// The content of the object to be uploaded. Sample content: a simple string "hello oss!". In actual scenarios, the content can be a file stream, a byte array, or other data types.
var content = "hello oss!";
// Convert the string to a UTF-8 encoded byte array and then wrap it into a MemoryStream.
// MemoryStream is used to process data streams in the memory and is suitable for uploading small files. We recommend that you use FileStream for large files.
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

// Call the PutObjectAsync method to asynchronously upload the object. You need to pass a request object that contains the bucket, key, and body.
// This method uploads the data in bodyStream to the key path of the specified bucket.
var result = await client.PutObjectAsync(new OSS.Models.PutObjectRequest()
{
    Bucket = bucket,    // The name of the destination bucket.
    Key = key,          // The unique key of the object in the bucket. 
    Body = bodyStream   // The content stream to be uploaded. In this example, it is string data in the memory.
});

// Print the upload result.
Console.WriteLine("PutObject done");  // A message indicates that the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}");  // The HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}");  // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:");  // The response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));  // Traverse and print all response headers.

Append upload

In a versioning-enabled bucket, you can call AppendObject only on the current version of an appendable object, not on historical versions.

Note
  • When you perform an AppendObject operation on the current version of an appendable object, OSS does not generate a historical version for the appendable object.

  • When you perform a PutObject or DeleteObject operation on the current version of an appendable object, OSS retains the appendable object as a historical version, and you can no longer append data to the object.

  • You cannot perform an AppendObject operation on the current version of a non-appendable object, such as a normal object or a delete marker.

The following code shows how to perform an append upload.

using System.Text; // Import the System.Text namespace to process character encodings, such as UTF-8 encoded strings.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-hangzhou"; // Required. Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
var bucket = "you bucket name";  // Required. Specify the name of the destination bucket. 
var endpoint = null as string;  // Optional. Specify the domain name used to access OSS. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var key = "your object key"; // Required. Specify the name of the object to which you want to append data. Format: folder/objectName.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as AccessKeys, 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 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 using the configuration information.
using var client = new OSS.Client(cfg);

// Define the first part of the content to be appended to the OSS object.
var content1 = "hello,";
// Define the second part of the content to be appended to the OSS object.
var content2 = "oss!";

// Call the AppendObjectAsync method to perform the first append operation.
var result1 = await client.AppendObjectAsync(new OSS.Models.AppendObjectRequest()
{
    // Specify the destination bucket.
    Bucket = bucket,
    // Specify the name of the destination object. 
    Key = key,
    // For the first append operation, the start position must be 0.
    Position = 0,
    Body = new MemoryStream(Encoding.UTF8.GetBytes(content1))
 });

// Call the AppendObjectAsync method to perform the second append operation, starting from the end position of the previous operation.
var result2 = await client.AppendObjectAsync(new OSS.Models.AppendObjectRequest()
{
     // The destination bucket remains unchanged.
    Bucket = bucket,
    // The name of the destination object remains unchanged.
    Key = key,
    // Continue writing from the end position of the previous append operation.
    Position = result1.NextAppendPosition,
    Body = new MemoryStream(Encoding.UTF8.GetBytes(content2))
});

// Print the upload result.
Console.WriteLine("AppendObject done"); // A message indicates that the operation is complete.
Console.WriteLine($"StatusCode: {result2.StatusCode}");  // The HTTP status code.
Console.WriteLine($"RequestId: {result2.RequestId}");   // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:"); // The response header information.
result2.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));   // Traverse and print all response headers.
Console.WriteLine($"NextAppendPosition: {result2.NextAppendPosition}"); // Output the start position for the next append operation.