Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 22, 2026

O download por intervalo permite que você baixe um intervalo específico de bytes de um objeto, em vez de baixar o objeto inteiro.

Observações

  • Neste tópico, utilizamos o endpoint público da região China (Hangzhou). Para 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 regiões e endpoints do OSS, consulte Regiões e endpoints.

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

  • O download por intervalo exige a permissão oss:GetObject. Para obter mais informações, consulte Conceder uma política personalizada.

Código de exemplo

O código de exemplo a seguir mostra como baixar um intervalo específico de bytes de um objeto.

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

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Download the object to D:\\localpath. After the object is downloaded, the local file is named examplefile.txt. If a file with the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
// If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located 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 based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    var getObjectRequest = new GetObjectRequest(bucketName, objectName);
    // Set the range to byte 20 to byte 100. 
    getObjectRequest.SetRange(20, 100);
    // Start range download. You can use setRange in getObjectRequest to perform range download and resumable download. 
    var obj = client.GetObject(getObjectRequest);
    // Download data and write the data to the file. 
    using (var requestStream = obj.Content)
    {
        byte[] buf = new byte[1024];
        var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
        var len = 0;
        while ((len = requestStream.Read(buf, 0, 1024)) != 0)
        {
            fs.Write(buf, 0, len);
        }
        fs.Close();
    }
    Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Get object failed. {0}", ex.Message);
}

A tabela a seguir descreve os parâmetros de GetObjectRequest.

Parâmetro

Descrição

Range

O intervalo de bytes a ser baixado.

ModifiedSinceConstraint

Retorna o objeto quando o horário informado é anterior ao horário real de modificação. Caso contrário, retorna o código de status HTTP 304 Not Modified.

UnmodifiedSinceConstraint

Retorna o objeto caso o horário informado seja igual ou posterior ao horário real de modificação. Se a condição não for atendida, retorna o código de status HTTP 412 Precondition Failed.

MatchingETagConstraints

Quando a ETag informada corresponde à ETag do objeto, o sistema retorna o objeto. Se não houver correspondência, retorna o código de status HTTP 412 Precondition Failed.

NonmatchingEtagConstraints

O sistema retorna o objeto se a ETag informada não corresponder à ETag do objeto. Caso contrário, retorna o código de status HTTP 304 Not Modified.

ResponseHeaderOverrides

Cabeçalhos de resposta personalizados para incluir na resposta do download.

Referências

  • Para obter o código de exemplo completo para download por intervalo, acesse GitHub.

  • Para a operação de API usada no download por intervalo, consulte GetObject.