只获取文件元信息
通过GetObjectMetadata方法可以只获取ObjectMeta而不获取文件的实体。代码如下:
- // 初始化OssClient
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- /// <summary>
- /// 获取文件的元信息。
- /// </summary>
- /// <param name="bucketName">存储空间的名称</param>
- /// <param name="key">文件在OSS上的名称</param>
- public void GetObjectMetadata(string bucketName, string key)
- {
- try
- {
- var metadata = client.GetObjectMetadata(bucketName, key);
- Console.WriteLine("Get object meta succeeded");
- Console.WriteLine("Content-Type:{0}", metadata.ContentType);
- Console.WriteLine("Cache-Control:{0}", metadata.CacheControl);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Get object meta failed. {0}", ex.Message);
- }
- }
进度条
OSS .Net SDK支持进度条功能,指示上传、下载的进度。下面的代码以 GetObject 为例,说明进度条功能的使用方法。
- using Aliyun.OSS;
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- public static void GetObjectProgress(string bucketName)
- {
- const string key = "GetObjectProgress";
- try
- {
- client.PutObject(bucketName, key, fileToUpload);
- var getObjectRequest = new GetObjectRequest(bucketName, key);
- 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", key);
- }
- 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 - TotalBytes:{0}, TransferredBytes:{1}",
- args.TotalBytes, args.TransferredBytes);
- }
提示:
- PutObject、AppendObject、UploadPart、ResumableUploadObject、GetObject都支持进度功能,完整代码请参考:GitHub。