All Products
Search
Document Center

Object Storage Service:OSS SDK for C# V2

Last Updated:May 27, 2026

GitHub | SDK Releases

Quick integration

Integrate OSS SDK for C# V2:

image

Prerequisites

  • Requires .NET Framework 4.7.1 or later.

  • Supports .NET Standard 2.0 and later.

  • Supports .NET 5.0 and later.

  • To install or update your .NET environment:

    • For .NET Framework: Go to the official Microsoft website to download and install .NET Framework 4.7.1 or later.

    • For .NET Standard: Ensure a compatible .NET implementation is installed (.NET Framework, .NET, or other supporting platforms).

    • For .NET: Go to the official .NET website to download and install .NET 5.0 or later.

Install the SDK

Use the latest OSS SDK for C# V2 to ensure the sample code runs as expected.

Install using NuGet

  • Check if NuGet is installed:

    • Ensure NuGet is installed in Visual Studio. If not, open Visual Studio Installer via Tools > Get Tools and Features, then select the .NET desktop development or ASP.NET and web development workload.

  • Open the project:

    • Create a project or open an existing project in Visual Studio.

  • Open the NuGet Package Manager:

    • In the menu bar, choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

  • Search for and install the SDK:

    • On the Browse tab of the NuGet Package Manager, search for AlibabaCloud.OSS.V2.

    • Select AlibabaCloud.OSS.V2 from the results. Ensure you select the latest stable version.

    • Click Install and wait for the installation to complete.

  • Verify the installation:

    • After installation, AlibabaCloud.OSS.V2 appears under References in Solution Explorer.

Install by importing the project

  • Clone the GitHub repository:

    • Open a command prompt or Git Bash and run the following command to clone the repository:

      git clone https://github.com/aliyun/alibabacloud-oss-csharp-sdk-v2.git
  • Add the project to your solution:

    • In Visual Studio, right-click your solution and choose Add > Existing Project....

    • Browse to the cloned source code directory, select the AlibabaCloud.OSS.V2.csproj file, and then click Open.

  • Add a project reference:

    • Right-click your project and choose Add > Reference....

    • In the dialog box that appears, go to the Projects tab, find and select the AlibabaCloud.OSS.V2 project, and then click OK.

Configure access credentials

Configure access credentials using the AccessKey pair of a RAM user.

  1. In the RAM console, create a RAM user with a Permanent AccessKey Pair. Save the AccessKey pair and grant AliyunOSSFullAccess permission to the RAM user.

  2. Configure environment variables using the AccessKey pair of the RAM user.

    Linux

    1. Run the following commands in the command-line interface to append the environment variable settings to the ~/.bashrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Run the following command to apply the configuration.

        source ~/.bashrc
      2. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to check the default shell type.

      echo $SHELL
      1. Follow the steps for your default shell type.

        Zsh

        1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Run the following command to apply the configuration.

          source ~/.zshrc
        3. Run the following commands to verify that the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Run the following command to apply the configuration.

          source ~/.bash_profile
        3. Run the following commands to verify that the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in Command Prompt.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Run the following commands to verify that the environment variables are configured.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Run the following commands to verify that the environment variables are configured.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Initialize the client

Initialize an OSSClient with the region and endpoint, then run the test code.

using System.Text; // Import the System.Text namespace to process character encoding, 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. 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 bucket = "your bucket name";  // Required. The name of the destination bucket.
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 key = "your object key"; // Required. The name of the object to upload. The format is folder/objectName.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if(endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// The content of the object to upload. Sample content: a simple string "hello oss!". In actual scenarios, the content can be a file stream or a byte array.
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 memory and is suitable for uploading small files. Use FileStream for large files.
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

// Call the PutObjectAsync method to asynchronously upload the object. You must pass a request object that contains the bucket, key, and body.
// This method uploads the data in bodyStream to the specified key path in 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 upload. In this example, it is the string data in memory.
});

// Print the upload result.
Console.WriteLine("PutObject done");  // A message that indicates 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.
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.

A successful upload returns the following output:

PutObject done
StatusCode: 200
RequestId: 68808D6D6A91E53037F7AAE9
Response Headers:
Server : AliyunOSS
Date : Wed, 23 Jul 2025 07:21:17 GMT
Connection : keep-alive
x-oss-request-id : 68808D6D6A91E53037F7AAE9
Vary : Origin
ETag : "968205D07B5A124D6ADA9336826C2C90"
x-oss-hash-crc64ecma : 11833582957755287462
x-oss-version-id : CAEQpgEYgYCA3fPQ2MEZIiA2ZmI4NGZkZWQzMWY0ZDZkOTFmMjUxYzRkNGMxODdkZg--
x-oss-server-time : 90
Content-Length : 0
Content-MD5 : loIF0HtaEk1q2pM2gmwskA==

Client configurations

What client configurations are supported?

Parameter name

Description

Example

Region

(Required) The region where the request is sent.

Configuration.Region = "cn-hangzhou"

Endpoint

Endpoint

Configuration.Endpoint = "oss-cn-hangzhou.aliyuncs.com"

RetryMaxAttempts

The maximum number of retries for a failed request.

Configuration.RetryMaxAttempts = 5

Retryer

The retry implementation for HTTP requests.

Configuration.Retryer = new Retry.DefaultRetryer()

HttpTransport

A custom HTTP client.

Configuration.HttpTransport = new HttpTransport()

CredentialsProvider

Specify the access credential (Required)

Configuration.CredentialsProvider = new EnvironmentVariableCredentialsProvider()

UsePathStyle

Specifies whether to use path-style access. By default, virtual-hosted-style access is used.

Configuration.UsePathStyle = true

UseCName

Specifies whether to use a custom domain name to access OSS. The default value is false.

Configuration.UseCName = true

ConnectTimeout

The timeout period for establishing a connection. Default value: 10 seconds.

Configuration.ConnectTimeout = TimeSpan.FromSeconds(30)

ReadWriteTimeout

The timeout period for reading and writing data. Default value: 20 seconds.

Configuration.ReadWriteTimeout = TimeSpan.FromMinutes(2)

InsecureSkipVerify

Specifies whether to skip SSL certificate verification. By default, SSL certificates are verified.

Configuration.InsecureSkipVerify = true

EnabledRedirect

Specifies whether to enable HTTP redirection. By default, HTTP redirection is disabled.

Configuration.EnabledRedirect = true

ProxyHost

Configure a proxy server.

Configuration.ProxyHost = "http://proxy.example.com:8080"

SignatureVersion

The signature version. Default value: v4.

Configuration.SignatureVersion = "v4"

DisableSsl

Disables HTTPS requests. HTTPS is enabled by default.

Configuration.DisableSsl = true

UseDualStackEndpoint

Specifies whether to use a dual-stack endpoint. The default value is false.

Configuration.UseDualStackEndpoint = true

UseAccelerateEndpoint

Specifies whether to use an acceleration endpoint. The default value is false.

Configuration.UseAccelerateEndpoint = true

UseInternalEndpoint

Specifies whether to use an internal endpoint. The default value is false.

Configuration.UseInternalEndpoint = true

DisableUploadCrc64Check

Disables the 64-bit cyclic redundancy check (CRC64) for uploads. By default, the check is enabled.

Configuration.DisableUploadCrc64Check = true

DisableDownloadCrc64Check

Disables the CRC64 check for downloads. By default, the check is enabled.

Configuration.DisableDownloadCrc64Check = true

AdditionalHeaders

The additional request headers to be signed. This parameter is valid only for V4 signatures.

Configuration.AdditionalHeaders = new List<string> { "x-oss-meta-*" }

UserAgent

Specifying additional information for the User-Agent

Configuration.UserAgent = "MyApp/1.0"

Use a custom domain name

Objects accessed through the default OSS endpoint may not preview in browsers. Map a custom domain name to access OSS to enable browser previews and CDN acceleration.

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 the region to cn-hangzhou.
var endpoint = "https://www.example-***.com";  // Required. Your custom domain name. Example: www.example-***.com.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Note that you must set the value to true to enable the CNAME option. Otherwise, you cannot use the custom domain name.
cfg.UseCName = true;

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Use the created client to perform subsequent operations...

Use an internal endpoint

Use an internal endpoint to access OSS in the same region, reducing traffic costs and increasing access speed.

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 the region to cn-hangzhou.
var endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";  // Optional. The internal endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// You can also set cfg.UseInternalEndpoint = true to configure the internal endpoint without the need to specify the internal endpoint.
// cfg.UseInternalEndpoint = true;

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Use the created client to perform subsequent operations...

Use a transfer acceleration endpoint

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 the region to cn-hangzhou.
var endpoint = "https://oss-accelerate.aliyuncs.com";  // Optional. The acceleration endpoint of the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to 'https://oss-accelerate.aliyuncs.com'.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// You can also set cfg.UseAccelerateEndpoint = true to configure the acceleration endpoint without the need to specify the acceleration endpoint.
// cfg.UseAccelerateEndpoint = true;

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Use the created client to perform subsequent operations...	

Use a private domain name

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 the region to cn-hangzhou.
var endpoint = "https://service.corp.example.com";  // Required. Your dedicated domain name. For example: https://service.corp.example.com.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Use the created client to perform subsequent operations...	

Use an Alibaba Gov Cloud endpoint

Configure an OSSClient with a Gov Cloud endpoint:

using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-north-2-gov-1"; // Required. The region where the bucket is located. For example, if the bucket is in the China North 2 (Ali Gov 1) region, set the region to cn-north-2-gov-1.
// Required. The internal endpoint of the region in which the bucket is located. For example, if the bucket is in the China North 2 (Ali Gov 1) region, set the endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
// To use the HTTP protocol, set the endpoint to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
var endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com";

// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Use the created client to perform subsequent operations...	

Access credential configurations

OSS supports multiple credential initialization methods. Choose one based on your authentication requirements.

Choosing an access credential

Credential provider initialization method

Scenarios

Whether a preceding AccessKey pair or STS token is required

Underlying credential

Credential validity period

Credential rotation or refresh method

Use the AccessKey pair of a RAM user

Applications that are deployed in a secure and stable environment that is not vulnerable to external attacks and require long-term access to Alibaba Cloud services without the need for frequent credential rotation.

Yes

AccessKey

Long-term

Manual rotation

Use an STS token

Applications that are deployed in an untrusted environment and require control over the validity period and permissions for access.

Yes

Security Token Service token

Temporary

Manual refresh

Use a RAM role ARN

Applications that require authorization to access Alibaba Cloud services, such as applications that need to access Alibaba Cloud services across Alibaba Cloud accounts.

Yes

Security Token Service token

Temporary

Auto-refresh

Use an ECS RAM role

Applications that are deployed on Alibaba Cloud ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes.

No

Security Token Service token

Temporary

Auto-refresh

Use an OIDC role ARN

Untrusted applications that are deployed on worker nodes of Container Service for Kubernetes.

No

Security Token Service token

Temporary

Auto-refresh

Use custom access credentials

If none of the preceding credential configuration methods meet your requirements, you can customize the method to obtain credentials.

Custom

Custom

Custom

Custom

Use the AccessKey pair of a RAM user

Initialize the credential provider with an AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user. Best suited for secure environments that require long-term OSS access without frequent credential rotation. Manual AccessKey pair maintenance is required.

Warning
  • An Alibaba Cloud account has full permissions on all resources. Leaked credentials expose your system to significant security risks. Use the AccessKey pair of a RAM user with minimum required permissions instead.

  • The AccessKey ID and AccessKey secret are shown only at creation time. Save them immediately — lost credentials cannot be recovered. Create an AccessKey pair.

Environment variables

  1. Configure environment variables using the AccessKey pair of a RAM user.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Apply the changes.

        source ~/.bashrc
      2. Check whether the environment variables have taken effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
      1. Configure environment variables based on the default shell type.

        Zsh

        1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Apply the changes.

          source ~/.zshrc
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Apply the changes.

          source ~/.bash_profile
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Check whether the environment variables take effect:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Check whether the environment variable takes effect:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

  2. After modifying the system environment variables, restart your IDE, CLI, and other runtime environments to load the updated values.

  3. Pass the credential information using environment variables.

    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 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.
    
    // Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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.
    cfg.Region = region;   
    // If an endpoint is specified, the default endpoint is overwritten. 
    if(endpoint != null) 
    {
        cfg.Endpoint = endpoint;
    } 
    
    // Create an OSS client instance based on the configurations.
    using var client = new OSS.Client(cfg);

Static credentials

Hard-code access credentials by setting the AccessKey pair directly.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing purposes only.

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 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 cfg = OSS.Configuration.LoadDefault();

// Specify the AccessKey ID and AccessKey secret of the RAM user.
var access_key_id = "yourAccessKeyId";
var access_key_secret = "yourAccessKeySecret";
// Create a static credential provider and explicitly set the AccessKey ID and AccessKey secret of the RAM user.
cfg.CredentialsProvider = new OSS.Credentials.StaticCredentialsProvider(access_key_id,access_key_secret);

// Set the region of the bucket.
cfg.Region = region;   
// If an endpoint is specified, the default endpoint is overwritten. 
if(endpoint != null) 
{
    cfg.Endpoint = endpoint;
} 

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

Use an STS token

Use temporary identity credentials (AccessKey ID, AccessKey secret, and security token) from STS to initialize the credential provider for temporary OSS access. This method requires manual STS token maintenance and refresh.

Important
  • Quickly obtain an STS token by calling AssumeRole.

  • Obtain an STS token using an SDK: Use an STS token to access OSS.

  • You must specify an expiration time when you generate an STS token. The STS token becomes invalid and cannot be used after it expires.

  • STS Endpoints.

Environment variables

  1. Set environment variables using temporary identity credentials.

    Mac OS X/Linux/Unix

    Warning
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair of a RAM user.

    • The AccessKey ID obtained from STS starts with `STS.`, for example, `STS.L4aBSCSJVMuKg5U1****`.

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Warning
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair of a RAM user.

    • The AccessKey ID obtained from STS starts with `STS.`, for example, `STS.L4aBSCSJVMuKg5U1****`.

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Pass the credential information using environment variables.

    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 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.
    
    // Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, 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, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN.
    cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
    // Set the region of the bucket.
    cfg.Region = region;   
    // If an endpoint is specified, the default endpoint is overwritten. 
    if(endpoint != null) 
    {
        cfg.Endpoint = endpoint;
    } 
    
    // Create an OSS client instance based on the configurations.
    using var client = new OSS.Client(cfg);

Static credentials

Hard-code access credentials by setting the temporary AccessKey pair directly.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing purposes only.

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 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 cfg = OSS.Configuration.LoadDefault();

// Specify the temporary AccessKey ID and AccessKey secret, not the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
// Note that the AccessKey ID obtained from STS starts with STS, as shown in the following code.
var access_key_id = "STS.****************";
var access_key_secret = "yourAccessKeySecret";
// Specify the obtained STS token.
var securityToken = "yourSecurityToken";
// Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey secret, and STS token.
cfg.CredentialsProvider = new OSS.Credentials.StaticCredentialsProvide(access_key_id, access_key_secret, securityToken);

// Set the region of the bucket.
cfg.Region = region;   
// If an endpoint is specified, the default endpoint is overwritten. 
if(endpoint != null) 
{
    cfg.Endpoint = endpoint;
} 

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

Use a RAM role ARN

Use a RAM role ARN to initialize the credential provider for cross-account OSS access. The Credentials tool automatically obtains and refreshes STS tokens via the AssumeRole operation. Use the policy parameter to restrict permissions.

Important
  • An Alibaba Cloud account has full permissions on all resources. Leaked credentials expose your system to significant security risks. Use the AccessKey pair of a RAM user with minimum required permissions instead.

  • The AccessKey ID and AccessKey secret are shown only at creation time. Save them immediately — lost credentials cannot be recovered. Create an AccessKey pair.

  • Obtain a RAM role ARN: Create a RAM role.

  1. Add the Aliyun.Credentials dependency.

    dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
  2. Configure the access credentials using an AccessKey pair and a RAM role ARN.

    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 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.
    
    // Alibaba Cloud credential configuration - Use a RAM role ARN.
    // For more information about credential types, see https://github.com/aliyun/credentials-csharp.
    var credConfig = new Aliyun.Credentials.Models.Config()
    {
        // Specify the credential type as a RAM role ARN.
        Type = "ram_role_arn",
        // Read the AccessKey ID from an environment variable.
        AccessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"),
        // Read the AccessKey secret from an environment variable.
        AccessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"),
        // The ARN of the RAM role. Format: acs:ram::USER_Id:role/ROLE_NAME.
        // You can also set this parameter using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        RoleArn = "acs:ram::***************:role/******",
        // The name of the role session. This parameter is used to identify the current session.
        RoleSessionName = "<RoleSessionName>",
        // Optional. The permission policy to be assumed.
        Policy = "<Policy>",
        // Optional. The validity period of the STS token in seconds.
        RoleSessionExpiration = 3600,
    };
    
    // Create a credential client instance to obtain a temporary access credential.
    var credClient = new Aliyun.Credentials.Client(credConfig);
    
    // Convert the common credential to a credential provider required by the OSS SDK.
    var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() =>
    {
        // Obtain the temporary credential.
        var credential = credClient.GetCredential();
    
        // Construct a credential object required by the OSS SDK.
        return new OSS.Credentials.Credentials(
            credential.AccessKeyId,      // The temporary AccessKey ID.
            credential.AccessKeySecret,  // The temporary AccessKey secret.
            credential.SecurityToken);   // The STS token.
    });
    
    // Load the default configurations of the OSS SDK.
    // By default, credential information is loaded from environment variables. In this example, it is overwritten by the custom credential.
    var cfg = OSS.Configuration.LoadDefault();
    // Set the OSS region.
    cfg.Region = region;
    // Set the custom credential provider.
    cfg.CredentialsProvider = credentialsProvider;
    
    // If a custom endpoint is specified, the default setting is overwritten.
    if (endpoint != null)
    {
        cfg.Endpoint = endpoint;
    }
    
    // Create an OSS client instance based on the configurations.
    using var client = new OSS.Client(cfg);
    
    // Create a paginator for the ListBuckets operation.
    // This is used to obtain all OSS buckets under the current account.
    var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());
    
    // Asynchronously iterate through the paginated results of the buckets.
    Console.WriteLine("Buckets:");
    await foreach (var page in paginator.IterPageAsync())
    {
        // Traverse the buckets on each page.
        foreach (var bucket in page.Buckets ?? [])
        {
            // Output bucket information: name, storage class, and location.
            Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
        }
    }
    

Use an ECS RAM role

For applications on ECS instances, ECI instances, or Container Service for Kubernetes worker nodes, use an ECS RAM role to initialize the credential provider. This associates a role with the instance or Container Service for Kubernetes node to auto-refresh STS tokens without manual credential management. Create a RAM role.

  1. Add the Aliyun.Credentials dependency.

    dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
  2. Configure the access credential using an ECS RAM role.

    using OSS = AlibabaCloud.OSS.V2;  // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
    using Aliyun.Credentials.Models;
    
    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.
    
    // Create a credential configuration and use an ECS RAM role for authentication.
    var credConfig = new Aliyun.Credentials.Models.Config()
    {
        // The credential type.
        Type = "ecs_ram_role",
        // The role name. This parameter is optional. If you do not specify this parameter, the role name is automatically obtained. We recommend that you set this parameter to reduce requests.
        RoleName = "<RoleName>"
    };
    
    // Create a credential client to obtain a temporary access credential.
    var credClient = new Aliyun.Credentials.Client(credConfig);
    
    // Convert the common credential to a credential provider required by the OSS SDK.
    var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() =>
    {
        // Obtain the temporary credential.
        var credential = credClient.GetCredential();
    
        // Construct a credential object required by the OSS SDK.
        return new OSS.Credentials.Credentials(
            credential.AccessKeyId,      // The temporary AccessKey ID.
            credential.AccessKeySecret,  // The temporary AccessKey secret.
            credential.SecurityToken);   // The STS token.
    });
    
    // Load the default configurations of the OSS client.
    var cfg = OSS.Configuration.LoadDefault();
    
    // Set the OSS region.
    cfg.Region = region;
    
    // Set the custom credential provider.
    cfg.CredentialsProvider = credentialsProvider;
    
    // If a custom endpoint is specified, the default setting is overwritten.
    if (endpoint != null)
    {
        cfg.Endpoint = endpoint;
    }
    
    // Create an OSS client instance based on the configurations.
    using var client = new OSS.Client(cfg);
    
    // Obtain all OSS buckets under the current role account.
    var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());
    
    // Asynchronously iterate through the paginated results of the buckets.
    Console.WriteLine("Buckets:");
    await foreach (var page in paginator.IterPageAsync())
    {
        // Traverse the buckets on each page.
        foreach (var bucket in page.Buckets ?? [])
        {
            // Output bucket information: name, storage class, and location.
            Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
        }
    }

Use an OIDC role ARN

For untrusted applications on Container Service for Kubernetes worker nodes, use RRSA (RAM Roles for Service Accounts) with an OIDC role ARN to isolate pod-level permissions. The cluster mounts OIDC token files to each pod and injects configuration into environment variables. The Credentials tool calls AssumeRoleWithOIDC to obtain STS tokens automatically, eliminating manual credential management. Isolate Pod permissions based on RRSA.

  1. Add the Aliyun.Credentials dependency.

    dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
  1. Configure the access credential using an OIDC role ARN.

    using OSS = AlibabaCloud.OSS.V2;  // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
    using Aliyun.Credentials.Models;
    
    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.
    
    // Create a credential configuration and use an OIDC role ARN for authentication.
    var credConfig = new Aliyun.Credentials.Models.Config()
    {
       // The credential type.
        Type = "oidc_role_arn",
        // Format: acs:ram::USER_Id:role/ROLE_NAME.
        // roleArn is optional. You can set the ALIBABA_CLOUD_ROLE_ARN environment variable instead.
        RoleArn = "<RoleArn>",
        // Format: acs:ram::USER_Id:oidc-provider/OIDC_IdP_name.
        // OIDCProviderArn is optional. You can set the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable instead.
        OIDCProviderArn = "<OIDCProviderArn>",
        // Format: path.
        // OIDCTokenFilePath is optional. You can set the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable instead.
        OIDCTokenFilePath = "/Users/xxx/xxx",
        // The name of the role session.
        RoleSessionName = "<RoleSessionName>",
        // Optional. The permission policy to be assumed.
        Policy = "<Policy>",
        // Optional. The validity period of the STS token.
        RoleSessionExpiration = 3600,
    };
    
    // Create a credential client to obtain a temporary access credential.
    var credClient = new Aliyun.Credentials.Client(credConfig);
    
    // Convert the common credential to a credential provider required by the OSS SDK.
    var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() =>
    {
        // Obtain the temporary credential.
        var credential = credClient.GetCredential();
    
        // Construct a credential object required by the OSS SDK.
        return new OSS.Credentials.Credentials(
            credential.AccessKeyId,      // The temporary AccessKey ID.
            credential.AccessKeySecret,  // The temporary AccessKey secret.
            credential.SecurityToken);   // The STS token.
    });
    
    // Load the default configurations of the OSS client.
    var cfg = OSS.Configuration.LoadDefault();
    
    // Set the OSS region.
    cfg.Region = region;
    
    // Set the custom credential provider.
    cfg.CredentialsProvider = credentialsProvider;
    
    // If a custom endpoint is specified, the default setting is overwritten.
    if (endpoint != null)
    {
        cfg.Endpoint = endpoint;
    }
    
    // Create an OSS client instance based on the configurations.
    using var client = new OSS.Client(cfg);
    
    // Obtain all OSS buckets under the current role account.
    var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());
    
    // Asynchronously iterate through the paginated results of the buckets.
    Console.WriteLine("Buckets:");
    await foreach (var page in paginator.IterPageAsync())
    {
        // Traverse the buckets on each page.
        foreach (var bucket in page.Buckets ?? [])
        {
            // Output bucket information: name, storage class, and location.
            Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
        }
    }

Use custom access credentials

Implement a custom credential provider if the preceding methods do not meet your requirements.

Use the Credentials.CredentialsProvideFunc interface

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 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.

// Explicitly set the access credentials. This is for demonstration purposes only. In actual projects, you can obtain the credentials from environment variables.
var AccessKeyId = "your AccessKeyId";  // Required. The AccessKey ID of the RAM user or the temporary AccessKey ID obtained from STS.
var AccessKeySecret = "your AccessKeySecret";  // Required. The AccessKey secret of the RAM user or the temporary AccessKey secret obtained from STS.
// var SecurityToken = "your STS Token";  // Optional. You can configure this variable if you use a temporary access credential.

// Convert the common credential to a credential provider required by the OSS SDK.
var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() =>
{
   
    // Use a long-term credential to construct a credential object required by the OSS SDK. 
    return new OSS.Credentials.Credentials(
        AccessKeyId,        // The AccessKey ID of the RAM user.
        AccessKeySecret);   // The AccessKey secret of the RAM user.

    // Use a temporary access credential to construct a credential object required by the OSS SDK. 
    // return new OSS.Credentials.Credentials(
    //     AccessKeyId,      // The temporary AccessKey ID.
    //     AccessKeySecret,  // The temporary AccessKey secret.
    //     SecurityToken);   // The STS token.
});

// Load the default configurations of the OSS client.
var cfg = OSS.Configuration.LoadDefault();

// Set the OSS region.
cfg.Region = region;

// Set the custom credential provider.
cfg.CredentialsProvider = credentialsProvider;

// If a custom endpoint is specified, the default setting is overwritten.
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);

// Obtain all OSS buckets under the current role account.
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());

// Asynchronously iterate through the paginated results of the buckets.
Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
    // Traverse the buckets on each page.
    foreach (var bucket in page.Buckets ?? [])
    {
        // Output bucket information: name, storage class, and location.
        Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
    }
}

Sample code

OSS SDK for C# V2 provides sample code for common operations.

Sample

GitHub sample file

Create a bucket (C# SDK V2)

PutBucket.cs

List buckets (C# SDK V2)

ListBuckets.cs

Check whether a bucket exists (C# SDK V2)

IsBucketExist.cs

Obtain the region of a bucket (C# SDK V2)

GetBucketLocation.cs

Obtain information about a bucket (C# SDK V2)

GetBucketInfo.cs

Obtain the storage capacity of a bucket (C# SDK V2)

GetBucketStat.cs

Delete a bucket (C# SDK V2)

DeleteBucket.cs

Simple upload (C# SDK V2)

PutObject.cs

Append upload (C# SDK V2)

AppendObject.cs

Multipart upload (C# SDK V2)

MultipartUpload.cs

Form upload (C# SDK V2)

PostObject.cs

Upload an object using a signed URL (C# SDK V2)

PresignPutObject.cs

Download an object to the memory (C# SDK V2)

GetObject.cs

Download an object to a local file (C# SDK V2)

GetObjectToFile.cs

Download an object using a signed URL (C# SDK V2)

PresignGetObject.cs

Copy an object (C# SDK V2)

CopyObject.cs

Check whether an object exists (C# SDK V2)

IsObjectExist.cs

List objects (C# SDK V2)

ListObjects.cs

Delete an object (C# SDK V2)

DeleteObject.cs

Manage symbolic links (C# SDK V2)

Set object tags (C# SDK V2)

PutObjectTagging.cs

Get object tags (C# SDK V2)

GetObjectTagging.cs

Delete object tags (C# SDK V2)

DeleteObjectTagging.cs

Manage bucket ACLs (C# SDK V2)

Manage object ACLs (C# SDK V2)

Manage versioning (C# SDK V2)

Synchronous processing (C# SDK V2)

ProcessObject.cs

Asynchronous processing (C# SDK V2)

AsyncProcessObject.cs