Todos os produtos
Search
Central de documentação

Object Storage Service:Resumable download (C# SDK V1)

Última atualização: Sep 22, 2026

O download de um objeto grande pode falhar se a rede estiver instável ou se ocorrerem outras exceções. Em alguns casos, a falha pode persistir mesmo após várias tentativas. Para resolver esse problema, o Object Storage Service (OSS) oferece o recurso de download retomável. Nesse processo, o OSS divide o objeto em várias partes e baixa cada uma separadamente. Após baixar todas as partes, o OSS as combina em um objeto completo.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre as regiões e os endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, demonstramos como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou se autenticar com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).

  • Para usar o download retomável, você precisa ter a permissão oss:GetObject. Para obter mais informações, consulte Conceder uma política personalizada.

Código de exemplo

O código a seguir mostra um exemplo de download retomável:

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

// Set yourEndpoint to the Endpoint of 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 = "yourEndpoint";
// 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 set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
// Download the object to a local file named examplefile.txt and save it to the specified local path (D:\\localpath). If the local file exists, it is overwritten. If the local file does not exist, it is created.
// If you do not specify a local path, the downloaded file is saved to the local path of the project where the sample program resides.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Specify the full path of the breakpoint record file. Example: D:\\localpath\\examplefile.txt.dcp.
// You need to specify the breakpoint record file only when the download is interrupted and a breakpoint record file is generated. After the download is complete, this file is deleted.
var checkpointDir = "D:\\localpath\\examplefile.txt.dcp";
// 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();

// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Set multiple parameters in DownloadObjectRequest.
    DownloadObjectRequest request = new DownloadObjectRequest(bucketName, objectName, downloadFilename)
    {
        // Specify the size of each shard for download in bytes.
        PartSize = 8 * 1024 * 1024,
        // Specify the number of concurrent threads.
        ParallelThreadCount = 3,
        // checkpointDir is used to save the progress of the resumable download. If a shard fails to download, the download resumes from the recorded breakpoint when you try again. If checkpointDir is set to null, the resumable download feature is disabled. The download restarts from the beginning after each failure.
        CheckpointDir = checkpointDir,
    };
    // Perform a resumable download.
    client.ResumableDownloadObject(request);
    Console.WriteLine("Resumable download object:{0} succeeded", objectName);
}
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);
}

Referências

Para obter mais informações sobre a operação da API de download retomável, consulte GetObject.