相关资源
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及以上版本。
您需要获取一个腾讯云 API 密钥,该密钥是您使用 COS SDK 各项功能的前提。
说明:
安装 SDK
我们提供
NuGet 的集成方式,您可以在工程的 csproj 文件里添加:<PackageReference Include="Tencent.QCloud.Cos.Sdk" Version="5.4.*" />
如果您是使用 .NET CLI,请使用如下命令安装:
dotnet add package Tencent.QCloud.Cos.Sdk
在 Visual Studio 项目中选择项目 > 添加引用 > 浏览 > COSXML-Compatible.dll 的方式添加 .NET(C#) SDK。
说明:
初始化 COS 服务
下面为您介绍如何使用 COS .NET SDK 完成一个基础操作,例如初始化客户端、创建存储桶、查询存储桶列表、上传对象、查询对象列表、下载对象和删除对象。
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 服务接口。初始化
说明:
//初始化 CosXmlConfigstring region = "COS_REGION"; //设置一个默认的存储桶地域CosXmlConfig config = new CosXmlConfig.Builder().IsHttps(true) //设置默认 HTTPS 请求.SetRegion(region) //设置一个默认的存储桶地域.SetDebugLog(true) //显示日志.Build(); //创建 CosXmlConfig 对象
设置 API 访问密钥
SDK 中提供了3种方式:持续更新的临时密钥、不变的临时密钥、永久密钥。
注意:
如果您一定要使用永久密钥,建议遵循 最小权限指引原则 对永久密钥的权限范围进行限制。
因为临时密钥在一定时效后过期,以下方式保证可以在过期后自动获取到新的临时密钥。
public class CustomQCloudCredentialProvider : DefaultSessionQCloudCredentialProvider{// 这里假设开始没有密钥,也可以用初始的临时密钥来初始化public CustomQCloudCredentialProvider(): base(null, null, 0L, null) {;}public override void Refresh(){//... 首先通过腾讯云请求临时密钥string tmpSecretId = "SECRET_ID"; //"临时密钥 SecretId", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048string tmpToken = "COS_TOKEN"; //"临时密钥 token", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048long tmpStartTime = 1546860702;//临时密钥有效开始时间,精确到秒long tmpExpiredTime = 1546862502;//临时密钥有效截止时间,精确到秒// 调用接口更新密钥SetQCloudCredential(tmpSecretId, tmpSecretKey,String.Format("{0};{1}", tmpStartTime, tmpExpiredTime), tmpToken);}}QCloudCredentialProvider cosCredentialProvider = new CustomQCloudCredentialProvider();
注意:
由于临时密钥在一定时效后过期,这种方式在过期后会请求失败,不建议使用。
string tmpSecretId = "SECRET_ID"; //"临时密钥 SecretId", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048string tmpToken = "COS_TOKEN"; //"临时密钥 token", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048long tmpExpireTime = 1546862502;//临时密钥有效截止时间,精确到秒QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(tmpSecretId, tmpSecretKey, tmpExpireTime, tmpToken);
string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); //用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140string secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); //用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140long durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);
初始化 CosXmlServer
使用
CosXmlConfig 与 QCloudCredentialProvider 初始化 CosXmlServer 服务类。服务类建议在程序中作为单例使用。CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);
访问 COS 服务
using COSXML;using COSXML.Auth;using COSXML.Model.Bucket;namespace COSXMLDemo{public class CreateBucketModel{public CosXml cosXml;// 初始化COS服务实例private void InitCosXml(){string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}CreateBucketModel(){InitCosXml();}public void PutBucket(){try{// 存储桶名称,此处填入格式必须为 BucketName-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";PutBucketRequest request = new PutBucketRequest(bucket);request.SetCosACL("private"); //定义 Object 的 acl 属性。有效值:private,public-read-write,public-read;默认值:private//执行请求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());}}public static void CreateBucketModelMain(){CreateBucketModel m = new CreateBucketModel();m.PutBucket();}}}
using COSXML;using COSXML.Auth;using COSXML.Model.Service;using COSXML.Model.Tag;namespace COSXMLDemo{public class ListBucketModel{public CosXml cosXml;// 初始化COS服务实例private void InitCosXml(){string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}ListBucketModel(){InitCosXml();}public void GetService(){try{GetServiceRequest request = new GetServiceRequest();//执行请求GetServiceResult result = cosXml.GetService(request);//得到所有的 bucketsList<ListAllMyBuckets.Bucket> allBuckets = result.listAllMyBuckets.buckets;foreach (var bucket in allBuckets){Console.WriteLine(bucket.name);}}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}public static void ListBucketModelMain(){ListBucketModel m = new ListBucketModel();m.GetService();}}}
using System.Runtime.InteropServices;using System.Text;using COSXML.Auth;using COSXML.Transfer;using COSXML;using COSXML.Model.Bucket;using COSXML.Model.Object;namespace COSXMLDemo{public class UploadObject {private CosXml cosXml;// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerprivate string bucket;public void InitParams(){bucket = Environment.GetEnvironmentVariable("BUCKET");}// 初始化COS服务实例private void InitCosXml(){//从Environment.GetEnvironmentVariable中设置变量,用户也可也直接赋值变量,如: string region = "ap-guagnzhou";string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}UploadObject(){//demo的自定义参数InitParams();//初始化COS服务InitCosXml();}public void PutObject(){try {// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";string key = "exampleobject"; //对象键string srcPath = @"temp-source-file";//本地文件绝对路径PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);//设置进度回调request.SetCosProgressCallback(delegate (long completed, long total) {Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));});PutObjectResult result = cosXml.PutObject(request);//打印返回结果Console.WriteLine(result.GetResultInfo());} catch (COSXML.CosException.CosClientException clientEx) {Console.WriteLine("CosClientException: " + clientEx);} catch (COSXML.CosException.CosServerException serverEx) {Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}public static void UploadObjectMain(){UploadObject domo = new UploadObject();//上传文件domo.PutObject();}}}
using COSXML;using COSXML.Auth;using COSXML.Model.Bucket;using COSXML.Model.Tag;namespace COSXMLDemo{public class ListObjectModel{public CosXml cosXml;// 初始化COS服务实例public string bucket;public void InitParams(){bucket = Environment.GetEnvironmentVariable("BUCKET");}// 初始化COS服务实例private void InitCosXml(){string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}ListObjectModel(){InitCosXml();InitParams();}// 获取对象多版本列表第一页数据public void ListObjectsVersioning(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-version-1250000000";ListBucketVersionsRequest request = new ListBucketVersionsRequest(bucket);//执行请求ListBucketVersionsResult result = cosXml.ListBucketVersions(request);//bucket的相关信息ListBucketVersions info = result.listBucketVersions;//请求结果状态Console.WriteLine(result.GetResultInfo());List<ListBucketVersions.Version> objects = info.objectVersionList;List<ListBucketVersions.CommonPrefixes> prefixes = info.commonPrefixesList;//返回信息Console.WriteLine(info);if (info.isTruncated){// 数据被截断,记录下数据下标this.keyMarker = info.nextKeyMarker;this.versionIdMarker = info.nextVersionIdMarker;}}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}private string keyMarker = "";private string versionIdMarker = "";// 获取对象多版本列表下一页数据public void ListObjectsVersioningNextPage(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-version-1250000000";ListBucketVersionsRequest request = new ListBucketVersionsRequest(bucket);// 上一页的数据结束下标request.SetKeyMarker(this.keyMarker);request.SetVersionIdMarker(this.versionIdMarker);//执行请求ListBucketVersionsResult result = cosXml.ListBucketVersions(request);//请求结果状态Console.WriteLine(result.GetResultInfo());ListBucketVersions info = result.listBucketVersions;Console.WriteLine(info.GetInfo());if (info.isTruncated){// 数据被截断,记录下数据下标this.keyMarker = info.nextKeyMarker;this.versionIdMarker = info.nextVersionIdMarker;}}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}public string nextMarker;// 获取第一页对象列表public void GetBucketFirstPage(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";GetBucketRequest request = new GetBucketRequest(bucket);//执行请求GetBucketResult result = cosXml.GetBucket(request);//bucket的相关信息COSXML.Model.Tag.ListBucket info = result.listBucket;if (info.isTruncated){// 数据被截断,记录下数据下标this.nextMarker = info.nextMarker;}Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}// 获取第二页对象列表public void GetBucketNextPage(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";GetBucketRequest request = new GetBucketRequest(bucket);//上一次拉取数据的下标request.SetMarker(this.nextMarker);//执行请求GetBucketResult result = cosXml.GetBucket(request);//bucket的相关信息COSXML.Model.Tag.ListBucket info = result.listBucket;Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}// 获取对象列表与子目录public void GetBucketWithDelimiter(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";GetBucketRequest request = new GetBucketRequest(bucket);//获取 a/ 下的对象以及子目录request.SetPrefix("dir/");request.SetDelimiter("/");//执行请求GetBucketResult result = cosXml.GetBucket(request);//bucket的相关信息COSXML.Model.Tag.ListBucket info = result.listBucket;// 对象列表List<COSXML.Model.Tag.ListBucket.Contents> objects = info.contentsList;// 子目录列表List<COSXML.Model.Tag.ListBucket.CommonPrefixes> subDirs = info.commonPrefixesList;Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}public static void ListObjectModelMain(){ListObjectModel demo = new ListObjectModel();//获取列表对象// demo.GetBucketFirstPage();// demo.GetBucketNextPage();// demo.GetBucketWithDelimiter();demo.ListObjectsVersioning();demo.ListObjectsVersioningNextPage();}}}
using COSXML;using COSXML.Auth;using COSXML.Model.Bucket;using COSXML.Model.Object;using COSXML.Model.Tag;using COSXML.Transfer;namespace COSXMLDemo{public class DownloadObject{public CosXml cosXml;// 初始化COS服务实例public string bucket;public void InitParams(){bucket = Environment.GetEnvironmentVariable("BUCKET");}// 初始化COS服务实例private void InitCosXml(){string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}DownloadObject(){//demo的自定义参数InitParams();//初始化COS服务InitCosXml();}public void GetObject(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";string key = "exampleobject"; //对象键string localDir = Path.GetTempPath();//本地文件夹string localFileName = "my-local-temp-file"; //指定本地保存的文件名GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName);request.SetCosProgressCallback(delegate (long completed, long total){Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));});//执行请求GetObjectResult result = cosXml.GetObject(request);Console.WriteLine(result.GetResultInfo());}catch (COSXML.CosException.CosClientException clientEx){Console.WriteLine("CosClientException: " + clientEx);}catch (COSXML.CosException.CosServerException serverEx){Console.WriteLine("CosServerException: " + serverEx.GetInfo());}}public static void DownloadObjectMain(){DownloadObject demo = new DownloadObject();demo.GetObject();}}}
注意:
对象被删除后,其对应的数据将无法再被访问。
using COSXML.Model.Object;using COSXML.Model.Tag;using COSXML.Model.Bucket;using COSXML.Auth;using COSXML;namespace COSXMLDemo{public class DeleteObjectModel{public CosXml cosXml;// 初始化COS服务实例public string bucket;public void InitParams(){bucket = Environment.GetEnvironmentVariable("BUCKET");}// 初始化COS服务实例private void InitCosXml(){string region = Environment.GetEnvironmentVariable("COS_REGION");CosXmlConfig config = new CosXmlConfig.Builder().SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224.Build();string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capistring secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capilong durationSecond = 600; //每次请求签名有效时长,单位为秒QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}DeleteObjectModel(){InitCosXml();InitParams();}// 删除对象public void DeleteObject(){try{// 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developerstring bucket = "examplebucket-1250000000";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());}}public static void DeleteObjectModelMain(){DeleteObjectModel m = new DeleteObjectModel();//删除对象m.DeleteObject();}}}