有奖捉虫:办公协同&微信生态&物联网文档专题 HOT

相关资源

SDK 源码下载请参见:XML .NET SDK
SDK 快速下载地址:XML .NET SDK
SDK 文档中的所有示例代码请参见 SDK 代码示例
SDK 更新日志请参见 ChangeLog
SDK 常见问题请参见:.NET(C#)SDK 常见问题
说明
如果您在使用 SDK 时遇到函数或方法不存在等错误,请先将 SDK 升级到最新版再重试。

第一步:集成 SDK

环境依赖

.NET SDK 基于 .NET Standard 2.0 开发。
Windows:安装 .NET Core 2.0 及以上版本,或者 .NET Framework 2.0 及以上版本。
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。
说明
兼容包中不包含高级上传、下载等功能的支持,详情参见 向下兼容指南

第二步:初始化 COS 服务

注意
建议用户 使用临时密钥 调用 SDK,通过临时授权的方式进一步提高 SDK 使用的安全性。申请临时密钥时,请遵循 最小权限指引原则,防止泄露目标存储桶或对象之外的资源。
如果您一定要使用永久密钥,建议遵循 最小权限指引原则 对永久密钥的权限范围进行限制。
下面为您介绍如何使用 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 region = "COS_REGION"; //设置一个默认的存储桶地域
CosXmlConfig config = new CosXmlConfig.Builder()
.IsHttps(true) //设置默认 HTTPS 请求
.SetRegion(region) //设置一个默认的存储桶地域
.SetDebugLog(true) //显示日志
.Build(); //创建 CosXmlConfig 对象

2. 提供访问凭证

SDK 中提供了3种方式:持续更新的临时密钥、不变的临时密钥、永久密钥。
方式1:持续更新的临时密钥
因为临时密钥在一定时效后过期,以下方式保证可以在过期后自动获取到新的临时密钥。
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/14048
string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
string tmpToken = "COS_TOKEN"; //"临时密钥 token", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
long tmpStartTime = 1546860702;//临时密钥有效开始时间,精确到秒
long tmpExpiredTime = 1546862502;//临时密钥有效截止时间,精确到秒
// 调用接口更新密钥
SetQCloudCredential(tmpSecretId, tmpSecretKey,
String.Format("{0};{1}", tmpStartTime, tmpExpiredTime), tmpToken);
}
}

QCloudCredentialProvider cosCredentialProvider = new CustomQCloudCredentialProvider();
方式2:不变的临时密钥(不建议)
注意
由于临时密钥在一定时效后过期,这种方式在过期后会请求失败,不建议使用。
string tmpSecretId = "SECRET_ID"; //"临时密钥 SecretId", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
string tmpSecretKey = "SECRET_KEY"; //"临时密钥 SecretKey", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
string tmpToken = "COS_TOKEN"; //"临时密钥 token", 临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
long tmpExpireTime = 1546862502;//临时密钥有效截止时间,精确到秒
QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
tmpSecretId, tmpSecretKey, tmpExpireTime, tmpToken);
方式3:永久密钥(不建议)
string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); //用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
string secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); //用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
long durationSecond = 600; //每次请求签名有效时长,单位为秒
QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(
secretId, secretKey, durationSecond);

3. 初始化 CosXmlServer

使用 CosXmlConfigQCloudCredentialProvider 初始化 CosXmlServer 服务类。服务类建议在程序中作为单例使用。
CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);

第三步:访问 COS 服务

创建存储桶

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());
}

上传对象

// 初始化 TransferConfig
TransferConfig transferConfig = new TransferConfig();

// 初始化 TransferManager
TransferManager transferManager = new TransferManager(cosXml, transferConfig);

String bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
String 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());
}

下载对象

// 初始化 TransferConfig
TransferConfig transferConfig = new TransferConfig();

// 初始化 TransferManager
TransferManager transferManager = new TransferManager(cosXml, transferConfig);

String bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
String 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());
}