All Products
Search
Document Center

Object Storage Service:Set object tags (C# SDK V2)

Last Updated:Mar 20, 2026

Use object tagging to attach key-value pairs to individual OSS objects for classification, lifecycle management, and access control. This page shows how to set tags on an object using the OSS SDK for C# V2.

Prerequisites

Before you begin, ensure that you have:

  • An OSS bucket in a supported region

  • The oss:PutObjectTagging permission granted to your RAM user. For details, see Grant custom permissions to a RAM user.

  • AccessKey credentials stored as environment variables (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET)

Set tags on an object

The following example sets two tags on an object in the China (Hangzhou) region (cn-hangzhou). The code loads credentials from environment variables and calls PutObjectTaggingAsync with a tag set.

Note: This example uses the public endpoint. To access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For supported regions and endpoints, see OSS regions and endpoints.
using OSS = AlibabaCloud.OSS.V2;

var region = "cn-hangzhou";        // The region where the bucket is located.
var endpoint = null as string;     // Optional. Override the default endpoint if needed.
var bucket = "examplebucket";      // The bucket name.
var key = "exampledir/exampleobject.txt"; // The object key.

// Load the default SDK configuration. Credentials are read from environment variables
// OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;

if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

using var client = new OSS.Client(cfg);

// Set tags on the object.
var result = await client.PutObjectTaggingAsync(new()
{
    Bucket = bucket,
    Key = key,
    Tagging = new()
    {
        TagSet = new()
        {
            Tags = [
                new OSS.Models.Tag() { Key = "tag1", Value = "value1" },
                new OSS.Models.Tag() { Key = "tag2", Value = "value2" },
            ]
        }
    }
});

Console.WriteLine("PutObjectTagging done");
Console.WriteLine($"StatusCode: {result.StatusCode}");
Console.WriteLine($"RequestId: {result.RequestId}");
Console.WriteLine("Response headers:");
result.Headers.ToList().ForEach(x => Console.WriteLine($"{x.Key}: {x.Value}"));

Replace the placeholder values in the code:

PlaceholderDescriptionExample
examplebucketThe bucket namemy-bucket
exampledir/exampleobject.txtThe object keylogs/app.log

References

For the complete sample, see PutObjectTagging.cs.