Tous les produits
Search
Centre de documentation

Object Storage Service:Copier un objet (C# SDK V1)

Dernière mise à jour :Aug 18, 2026

Copiez des objets au sein d'un même bucket ou entre des buckets situés dans la même région.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région qu'OSS, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Cette rubrique explique comment créer une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation (C# SDK V1).

  • Vous devez disposer des autorisations de lecture sur l'objet source et des autorisations de lecture/écriture sur le bucket de destination.

  • Les buckets source et de destination ne doivent pas avoir de politiques de rétention configurées. Dans le cas contraire, la copie échoue et l'erreur The object you specified is immutable. est renvoyée.

  • La copie inter-régions n'est pas prise en charge. Par exemple, vous ne pouvez pas copier un objet d'un bucket situé en Chine (Hangzhou) vers un bucket situé en Chine (Qingdao).

Copier un petit fichier

Le code suivant montre comment copier un petit objet :

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the source bucket. Example: srcexamplebucket.
var sourceBucket = "srcexamplebucket";
// Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt.
var sourceObject = "srcdir/scrobject.txt";
// Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket.
var targetBucket = "destbucket";
// Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt.
var targetObject = "destdir/destobject.txt";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    var metadata = new ObjectMetadata();
    // Set custom metadata. Custom metadata is a key-value pair. For example, set the key to mk1 and the value to mv1.
    metadata.AddHeader("mk1", "mv1");
    metadata.AddHeader("mk2", "mv2");
    var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
    {
        // If NewObjectMetadata is null, the metadata of the source object is copied (COPY mode). If NewObjectMetadata is not null, the metadata of the source object is overwritten (REPLACE mode).
        NewObjectMetadata = metadata 
    };
    // Copy the object.
    client.CopyObject(req);
    Console.WriteLine("Copy object succeeded");
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

Copier un grand fichier

  • Copie multipartie

    Pour les objets de plus de 1 Go, utilisez la copie multipartie (UploadPartCopy). Le processus se déroule en trois étapes :

    1. Utilisez la méthode InitiateMultipartUploadRequest pour initialiser un téléchargement multipartie.

    2. Utilisez la méthode UploadPartCopy pour copier les parties.

    3. Utilisez la méthode CompleteMultipartUpload pour finaliser la copie de l'objet.

    Le code suivant montre comment effectuer une copie multipartie :

    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    // Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the name of the source bucket. Example: srcexamplebucket.
    var sourceBucket = "srcexamplebucket";
    // Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt.
    var sourceObject = "srcdir/scrobject.txt";
    // Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket.
    var targetBucket = "destbucket";
    // Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt.
    var targetObject = "destdir/destobject.txt";
    var uploadId = "";
    var partSize = 50 * 1024 * 1024;
    // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
    const string region = "cn-hangzhou";
    
    // Create a ClientConfiguration instance and modify the default parameters as needed.
    var conf = new ClientConfiguration();
    
    // Use Signature V4.
    conf.SignatureVersion = SignatureVersion.V4;
    
    // Create an OssClient instance.
    var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
    client.SetRegion(region);
    try
    {
        // Initialize the copy task. You can use InitiateMultipartUploadRequest to specify the metadata of the destination object.
        var request = new InitiateMultipartUploadRequest(targetBucket, targetObject);
        var result = client.InitiateMultipartUpload(request);
        // Print the upload ID.
        uploadId = result.UploadId;
        Console.WriteLine("Init multipart upload succeeded, Upload Id: {0}", result.UploadId);
        // Calculate the number of parts.
        var metadata = client.GetObjectMetadata(sourceBucket, sourceObject);
        var fileSize = metadata.ContentLength;
        var partCount = (int)fileSize / partSize;
        if (fileSize % partSize != 0)
        {
            partCount++;
        }
        // Start the multipart copy.
        var partETags = new List<PartETag>();
        for (var i = 0; i < partCount; i++)
        {
            var skipBytes = (long)partSize * i;
            var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
            // Create an UploadPartCopyRequest. You can use UploadPartCopyRequest to specify conditions.
            var uploadPartCopyRequest = new UploadPartCopyRequest(targetBucket, targetObject, sourceBucket, sourceObject, uploadId)
                {
                    PartSize = size,
                    PartNumber = i + 1,
                    // BeginIndex specifies the starting position of the part to be copied.
                    BeginIndex = skipBytes
                };
            // Call the uploadPartCopy method to copy each part.
            var uploadPartCopyResult = client.UploadPartCopy(uploadPartCopyRequest);
            Console.WriteLine("UploadPartCopy : {0}", i);
            partETags.Add(uploadPartCopyResult.PartETag);
        }
        // Complete the multipart copy.
        var completeMultipartUploadRequest =
        new CompleteMultipartUploadRequest(targetBucket, targetObject, uploadId);
        // partETags is a list of PartETags saved during the multipart upload. After OSS receives this list, it verifies each part. If all parts are valid, OSS combines them into a complete object.
        foreach (var partETag in partETags)
        {
            completeMultipartUploadRequest.PartETags.Add(partETag);
        }
        var completeMultipartUploadResult = client.CompleteMultipartUpload(completeMultipartUploadRequest);
        Console.WriteLine("CompleteMultipartUpload succeeded");
    }
    catch (OssException ex)
    {
        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
            ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
  • Copie avec reprise

    Si une tâche de copie est interrompue, vous pouvez la reprendre à partir du point d'interruption.

    Le code suivant montre comment effectuer une copie avec reprise :

    using Aliyun.OSS;
    // Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the name of the source bucket. Example: srcexamplebucket.
    var sourceBucket = "srcexamplebucket";
    // Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt.
    var sourceObject = "srcdir/scrobject.txt";
    // Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket.
    var targetBucket = "destbucket";
    // Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt.
    var targetObject = "destdir/destobject.txt";
    // Specify the file that records the copy results. The progress information is saved to this file. If the copy task fails, it resumes from the recorded breakpoint. After the copy is complete, this file is deleted.
    var checkpointDir = @"yourCheckpointDir";
    // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
    const string region = "cn-hangzhou";
    
    // Create a ClientConfiguration instance and modify the default parameters as needed.
    var conf = new ClientConfiguration();
    
    // Use Signature V4.
    conf.SignatureVersion = SignatureVersion.V4;
    
    // Create an OssClient instance.
    var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
    client.SetRegion(region);
    try
    {
        var request = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject);
        // The checkpointDir directory saves the intermediate state for resumable copy. This allows the task to resume after a failure. If checkpointDir is null, the resumable copy feature is disabled, and the copy task starts over each time.
        client.ResumableCopyObject(request, checkpointDir);
        Console.WriteLine("Resumable copy new object:{0} succeeded", request.DestinationKey);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Resumable copy new object failed, {0}", ex.Message);
    }

Références

  • Copier un petit objet

    • Pour l'exemple de code complet utilisé pour copier un petit objet, consultez GitHub.

    • Pour plus d'informations sur l'opération API utilisée pour copier un petit objet, consultez CopyObject.

  • Copier un grand objet

    • Pour l'exemple de code complet utilisé pour copier un grand objet, consultez GitHub.

    • Pour plus d'informations sur l'opération API utilisée pour copier un grand objet, consultez UploadPartCopy.

  • Copie avec reprise

    Pour l'exemple de code complet utilisé pour une copie avec reprise, consultez GitHub.