进度条用于指示上传或下载的进度。
下载进度条的完整代码请详见GitHub。
下面的代码以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() { var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; var objectName = "<yourObjectName>"; // 创建OssClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var getObjectRequest = new GetObjectRequest(bucketName, objectName); getObjectRequest.StreamTransferProgress += streamProgressCallback; // 下载文件。 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) { // 处理读取的数据(此处代码省略)。 } } 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); } } }