Todos os produtos
Search
Central de documentação

Object Storage Service:Copy objects (C# SDK V2)

Última atualização: Aug 24, 2026

Use o método CopyObjectAsync no C# SDK V2 para copiar objetos (menores que 5 GiB) de um bucket de origem para um bucket de destino igual ou diferente na mesma região.

Considerações

  • O código de exemplo usa o ID da região China (Hangzhou) (cn-hangzhou) e o endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para mais informações, consulte OSS regions and endpoints.

  • Para copiar um objeto, você precisa ter permissões de leitura no objeto de origem e permissões de lista de controle de acesso (leitura e gravação) no bucket de destino.

  • Os buckets de origem e de destino devem estar na mesma região. Por exemplo, não é possível copiar objetos de um bucket na região China (Hangzhou) para um bucket na região China (Qingdao).

  • Ao copiar objetos, verifique se nenhum dos buckets (origem ou destino) possui política de retenção. Caso contrário, o sistema retorna o erro The object you specified is immutable..

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm permissões por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.

API

Action

Descrição

CopyObject

oss:GetObject

Copia objetos dentro de um bucket ou entre buckets na mesma região.

oss:PutObject

oss:GetObjectVersion

Necessária também ao especificar a versão do objeto de origem via versionId.

oss:GetObjectTagging

Necessárias ao copiar tags do objeto por meio de x-oss-tagging.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Necessária também ao especificar as tags de uma versão específica do objeto de origem via versionId.

kms:GenerateDataKey

Ambas as permissões são necessárias se os metadados do objeto de destino contiverem X-Oss-Server-Side-Encryption: KMS durante a cópia.

kms:Decrypt

Código de exemplo

O código a seguir copia um objeto menor que 5 GiB do bucket de origem para o bucket de destino.

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

var region = "cn-hangzhou";  // Required. Specify the region of the bucket. In this example, the region is China (Hangzhou), and the region ID is cn-hangzhou
var endpoint = null as string;  // Optional. Specify the endpoint used to access OSS. In this example, the endpoint for China (Hangzhou) is https://oss-cn-hangzhou.aliyuncs.com
var srcBucket = "your srcBucket name";  // Required. Specify the name of the source bucket
var srcKey = "your srcKey name";  // Required. Specify the name of the object in the source bucket in the folder/objectName format
var dstBucket = "your dstBucket name";  // Required. Specify the name of the destination bucket
var dstKey = "your dstkey name";  // Required. Specify the name of the object in the destination bucket in the folder/objectName format

// Load the default configuration of the OSS SDK, which automatically reads credential information (such as AccessKey) from environment variables
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set to use environment variables for credentials authentication (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region in the configuration
cfg.Region = region;   
// If an endpoint is specified, override 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); 

// Call the CopyObjectAsync method to perform the OSS object copy operation
var result = await client.CopyObjectAsync(new OSS.Models.CopyObjectRequest()
{
    Bucket = dstBucket,
    Key = dstKey,
    SourceBucket = srcBucket,
    SourceKey = srcKey
});

// Display the upload result
Console.WriteLine("CopyObject done");  // Indicate that the operation is complete
Console.WriteLine($"StatusCode: {result.StatusCode}");  // HTTP status code
Console.WriteLine($"RequestId: {result.RequestId}");  // RequestId, used for troubleshooting by Alibaba Cloud
Console.WriteLine("Response Headers:");  // Response header information
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));  // Traverse and print all response headers

Referências

Para obter o código de exemplo completo, consulte CopyObject.cs.