Todos os produtos
Search
Central de documentação

Object Storage Service:Progress bar chart (C# SDK V1)

Última atualização: Jul 03, 2026

Uma barra de progresso exibe o andamento de um upload ou download.

Observações

  • Este tópico usa 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 obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

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

Código de exemplo

O código a seguir mostra como usar uma barra de progresso. O exemplo utiliza o método GetObject.

using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace GetObjectProgress
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.GetObjectProgress();
            Console.ReadKey();
        }
        public static void GetObjectProgress()
        {
            // 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 = "exampledir/exampleobject.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 getObjectRequest = new GetObjectRequest(bucketName, objectName);
                getObjectRequest.StreamTransferProgress += streamProgressCallback;
                // Download the file.
                var ossObject = client.GetObject(getObjectRequest);
                using (var stream = ossObject.Content)
                {
                    var buffer = new byte[1024 * 1024];
                    var bytesRead = 0;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        // Process the read data. This part of the code is omitted.
                    }
                }
                Console.WriteLine("Get 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);
            }
        }
        private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
        {
            System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
                args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
        }
    }
}

Referências

Para obter o código completo que demonstra o uso da barra de progresso em downloads de arquivos, consulte o exemplo no GitHub.