Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 24, 2026

Um gráfico de barra de progresso exibe o andamento de um upload ou download.

Observações

  • Neste tópico, o endpoint público da região China (Hangzhou) é usado como referência. 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 Regions and endpoints.

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

Código de exemplo

O código a seguir demonstra como usar um gráfico de 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 o código de exemplo completo sobre como usar um gráfico de barra de progresso em downloads de arquivos, consulte o exemplo no GitHub.