一、相关资源
·SDK 源码下载请参见:XML .NET SDK。
·SDK 快速下载地址:XML .NET SDK。
·SDK 文档中的所有示例代码请参见 SDK 代码示例。
·SDK 更新日志请参见 ChangeLog。
·SDK 常见问题请参见:.NET(C#)SDK 常见问题。
注意:说明:
注意:如果你在使用 SDK 时遇到函数或方法不存在等错误,请先将 SDK 升级到最新版再重试。
二、环境依赖
.NET SDK 基于 .NET Standard 2.0开发。
·Windows:安装 .NET Core 2.0及以上版本,或者 .NET Framework 4.5及以上版本。
·Linux/Mac:安装 .NET Core 2.0及以上版本。
三、添加 SDK
我们提供 Nuget 的集成方式,你可以在工程的 csproj 文件里添加:
<PackageReference Include="Tencent.QCloud.Cos.Sdk" Version="5.4.*" />
如果你是使用 .NET CLI,请使用如下命令安装:
dotnet add package Tencent.QCloud.Cos.Sdk
如果你是用于目标框架 .Net Framework 4.0及以下版本的开发,请下载 Releases 并使用 COSXML-Compatible.dll 文件。
在 Visual Studio 项目中选择项目 > 添加引用 > 浏览 > COSXML-Compatible.dll 的方式添加 .NET(C#) SDK。
注意:说明:
注意:兼容包中不包含高级上传、下载等功能的支持,详情参见 向下兼容指南。
四、步骤2:初始化 COS 服务
下面为你介绍如何使用 COS .NET SDK 完成一个基础操作,例如初始化客户端、创建存储桶、查询存储桶列表、上传对象、查询对象列表、下载对象和删除对象。
注意:说明:
注意:关于文章中出现的 SecretId、SecretKey、Bucket 等名称的含义和获取方式请参见 COS 术语信息。
SDK 中常用的命名空间有:
using COSXML;using COSXML.Auth;using COSXML.Model.Object;using COSXML.Model.Bucket;using COSXML.CosException;
在执行任何和 COS 服务相关请求之前,都需要先实例化CosXmlConfig , QCloudCredentialProvider , CosXmlServer3个对象。其中:
·CosXmlConfig提供配置 SDK 接口。
·QCloudCredentialProvider提供设置密钥信息接口。
·CosXmlServer提供各种 COS API 服务接口。
注意:说明:
注意:下述初始化示例中使用的临时密钥,其生成和使用可参见 临时密钥生成及使用指引。
五、1. 初始化服务设置
//初始化 CosXmlConfig string appid = "1250000000";//设置腾讯云账户的账户标识 APPIDstring region = "COS_REGION"; //设置一个默认的存储桶地域CosXmlConfig config = new CosXmlConfig.Builder() .IsHttps(true) //设置默认 HTTPS 请求 .SetRegion(region) //设置一个默认的存储桶地域 .SetDebugLog(true) //显示日志 .Build(); //创建 CosXmlConfig 对象
六、2. 提供访问凭证
SDK 中提供了3种方式:永久密钥、持续更新的临时密钥、不变的临时密钥。
方式1:永久密钥
string secretId = "SECRET_ID"; //"云 API 密钥 SecretId";string secretKey = "SECRET_KEY"; //"云 API 密钥 SecretKey";long durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider( secretId, secretKey, durationSecond);
方式2:持续更新的临时密钥
因为临时密钥在一定时效后过期,以下方式保证可以在过期后自动获取到新的临时密钥。
public class CustomQCloudCredentialProvider : DefaultSessionQCloudCredentialProvider{ // 这里假设开始没有密钥,也可以用初始的临时密钥来初始化 public CustomQCloudCredentialProvider(): base(null, null, 0L, null) { ; } public override void Refresh() { //… 首先通过腾讯云请求临时密钥 string tmpSecretId = "SECRET_ID"; //"临时密钥 SecretId"; string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey"; string tmpToken = "COS_TOKEN"; //"临时密钥 token"; long tmpStartTime = 1546860702;//临时密钥有效开始时间,精确到秒 long tmpExpiredTime = 1546862502;//临时密钥有效截止时间,精确到秒 // 调用接口更新密钥 SetQCloudCredential(tmpSecretId, tmpSecretKey, String.Format("{0};{1}", tmpStartTime, tmpExpiredTime), tmpToken); }}QCloudCredentialProvider cosCredentialProvider = new CustomQCloudCredentialProvider();
方式3:不变的临时密钥(不建议)
注意:由于临时密钥在一定时效后过期,这种方式在过期后会请求失败,不建议使用。
string tmpSecretId = "SECRET_ID"; //"临时密钥 SecretId";string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey";string tmpToken = "COS_TOKEN"; //"临时密钥 token";long tmpExpireTime = 1546862502;//临时密钥有效截止时间,精确到秒QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider( tmpSecretId, tmpSecretKey, tmpExpireTime, tmpToken);
七、3. 初始化 CosXmlServer
使用 CosXmlConfig 与 QCloudCredentialProvider 初始化 CosXmlServer 服务类。服务类建议在程序中作为单例使用。
CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);
八、创建存储桶
try{ string bucket = "examplebucket-1250000000"; //格式:BucketName-APPID PutBucketRequest request = new PutBucketRequest(bucket); //执行请求 PutBucketResult result = cosXml.PutBucket(request); //请求成功 Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){ //请求失败 Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){ //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo());}
九、查询存储桶列表
try{ GetServiceRequest request = new GetServiceRequest(); //执行请求 GetServiceResult result = cosXml.GetService(request); //得到所有的 buckets List<ListAllMyBuckets.Bucket> allBuckets = result.listAllMyBuckets.buckets;}catch (COSXML.CosException.CosClientException clientEx){ //请求失败 Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){ //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo());}
十、上传对象
// 初始化 TransferConfigTransferConfig transferConfig = new TransferConfig();// 初始化 TransferManagerTransferManager transferManager = new TransferManager(cosXml, transferConfig);String bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPIDString cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键String srcPath = @"temp-source-file";//本地文件绝对路径// 上传对象COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);uploadTask.SetSrcPath(srcPath);uploadTask.progressCallback = delegate (long completed, long total){ Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));};try { COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask); Console.WriteLine(result.GetResultInfo()); string eTag = result.eTag;} catch (Exception e) { Console.WriteLine("CosException: " + e);}
十一、查询对象列表
try{ string bucket = "examplebucket-1250000000"; //格式:BucketName-APPID GetBucketRequest request = new GetBucketRequest(bucket); //执行请求 GetBucketResult result = cosXml.GetBucket(request); //bucket的相关信息 ListBucket info = result.listBucket; if (info.isTruncated) { // 数据被截断,记录下数据下标 this.nextMarker = info.nextMarker; }}catch (COSXML.CosException.CosClientException clientEx){ //请求失败 Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){ //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo());}
十二、下载对象
// 初始化 TransferConfigTransferConfig transferConfig = new TransferConfig();// 初始化 TransferManagerTransferManager transferManager = new TransferManager(cosXml, transferConfig);String bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPIDString cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键string localDir = System.IO.Path.GetTempPath();//本地文件夹string localFileName = "my-local-temp-file"; //指定本地保存的文件名// 下载对象COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath, localDir, localFileName);downloadTask.progressCallback = delegate (long completed, long total){ Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));};try { COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await transferManager.DownloadAsync(downloadTask); Console.WriteLine(result.GetResultInfo()); string eTag = result.eTag;} catch (Exception e) { Console.WriteLine("CosException: " + e);}
十三、删除对象
try{ string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 DeleteObjectRequest request = new DeleteObjectRequest(bucket, key); //执行请求 DeleteObjectResult result = cosXml.DeleteObject(request); //请求成功 Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){ //请求失败 Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){ //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo());}