快速入门

最近更新时间:2019-08-01 15:31:47

下载与安装

相关资源

环境依赖

  • COS XML C# SDK 源码基于 .NET 4.0 开发,依赖于 newtonsoft.json 库。
  • Windows:安装 .NET 2.0及以上版本,Visual Studio 2010及以上版本.
  • Linux/Mac:安装 Mono 3.12及以上版本。

安装 SDK

SDK 包含的 DLL 库文件为 COSXML.dll 和 Newtonsoft.Json.dll,您可以通过以下方式安装 SDK:

  • DLL 引用方式
    获取 SDK 开发包,将其中的 DLL 文件,导入到工程。
  • 项目引入方式
    获取 源码,将其作为项目导入。
  • Nuget 引用方式
    在 Nuget 包管理器中找到 Tencent.QCloud.Cos.Sdk ,单击安装即可。

开始使用

下面为您介绍如何使用 COS C# 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 服务接口。
//初始化 CosXmlConfig 
string appid = "1250000000";//设置腾讯云账户的账户标识 APPID
string region = "ap-beijing"; //设置一个默认的存储桶地域
CosXmlConfig config = new CosXmlConfig.Builder()
    .SetConnectionTimeoutMs(60000)  //设置连接超时时间,单位 毫秒 ,默认 45000ms
    .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位 毫秒 ,默认 45000ms
    .IsHttps(true)  //设置默认 https 请求
    .SetAppid(appid)  //设置腾讯云账户的账户标识 APPID
    .SetRegion(region)  //设置一个默认的存储桶地域
    .SetDebugLog(true)  //显示日志
    .Build();  //创建 CosXmlConfig 对象

//初始化 QCloudCredentialProvider ,SDK中提供了3种方式:永久密钥 、 临时密钥  、 自定义 
QCloudCredentialProvider cosCredentialProvider  =  null;

//方式1, 永久密钥
string secretId = "COS_SECRETID"; //"云 API 密钥 SecretId";
string secretKey = "COS_SECRETKEY"; //"云 API 密钥 SecretKey";
long durationSecond = 600;  //secretKey 有效时长,单位为 秒
cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);

//方式2, 临时密钥
string tmpSecretId = "COS_SECRETID"; //"临时密钥 SecretId";
string tmpSecretKey = "COS_SECRETKEY"; //"临时密钥 SecretKey";
string tmpToken = "COS_TOKEN"; //"临时密钥 token";
long tmpExpireTime = 1546862502;//临时密钥有效截止时间
cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(tmpSecretId,tmpSecretKey,tmpExpireTime,tmpToken);

//方式3,自定义方式提供密钥信息, 继承 QCloudCredentialProvider 并 重写 GetQCloudCredentials() 方法
public class MyQCloudCredentialProvider : QCloudCredentialProvider
{
    public override QCloudCredentials GetQCloudCredentials()
    {
        string secretId = "COS_SECRETID"; //密钥 SecretId
        string secretKey = "COS_SECRETKEY"; //密钥 SecretKey
        string keyTime = "密钥 有效期间"; //1546862502;1546863102
        return new QCloudCredentials(secretId, secretKey, keyTime);
    }

    public override void Refresh()
    {
        //更新 密钥信息
    }
}
cosCredentialProvider = new MyQCloudCredentialProvider();

//初始化 CosXmlServer
CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);

创建存储桶

try
{
    string bucket = "examplebucket-1250000000"; //存储桶名称 格式:BucketName-APPID
    PutBucketRequest request = new PutBucketRequest(bucket);
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //执行请求
    PutBucketResult result = cosXml.PutBucket(request);
    //请求成功
    Console.WriteLine(result.GetResultInfo());
}
catch (COSXML.CosException.CosClientException clientEx)
{
    //请求失败
    Console.WriteLine("CosClientException: " + clientEx.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}

查询存储桶列表

try
{
    GetServiceRequest request = new GetServiceRequest();
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //执行请求
    GetServiceResult result = cosXml.GetService(request);
    //请求成功
    Console.WriteLine(result.GetResultInfo());
}
catch (COSXML.CosException.CosClientException clientEx)
{
    //请求失败
    Console.WriteLine("CosClientException: " + clientEx.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{    
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}

上传对象

try
{
    string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
    string key = "exampleobject"; //对象在存储桶中的位置,即称对象键.
    string srcPath = @"F:\exampleobject";//本地文件绝对路径
    PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //设置进度回调
    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.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}

**// 大文件需要使用分片上传(), 可参考 SDK 中封装的 TransferManager  和 COSXMLUploadTask 类, 如下示例 **
TransferManager transferManager = new TransferManager(cosXml, new TransferConfig());
COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, null, key);
uploadTask.SetSrcPath(srcPath);
uploadTask.progressCallback = delegate (long completed, long total)
{
    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
};
uploadTask.successCallback = delegate (CosResult cosResult) 
{
    COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = cosResult as COSXML.Transfer.COSXMLUploadTask.UploadTaskResult;
    Console.WriteLine(result.GetResultInfo());
};
uploadTask.failCallback = delegate (CosClientException clientEx, CosServerException serverEx) 
{
    if (clientEx != null)
    {
        Console.WriteLine("CosClientException: " + clientEx.Message);
    }
    if (serverEx != null)
    {
        Console.WriteLine("CosServerException: " + serverEx.GetInfo());
    }
};
transferManager.Upload(uploadTask);

查询对象列表

try
{
    string bucket = "examplebucket-1250000000"; //格式:BucketName-APPID
    GetBucketRequest request = new GetBucketRequest(bucket);
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //执行请求
    GetBucketResult result = cosXml.GetBucket(request);
    //请求成功
    Console.WriteLine(result.GetResultInfo());
}
catch (COSXML.CosException.CosClientException clientEx)
{
    //请求失败
    Console.WriteLine("CosClientException: " + clientEx.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}

下载对象

try
{
    string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
    string key = "exampleobject"; //对象在存储桶中的位置,即称对象键.
    string localDir = @"F:\";//下载到本地指定文件夹
    string localFileName = "exampleobject"; //指定本地保存的文件名
    GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName);
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //设置进度回调
    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.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}

删除对象

try
{
    string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
    string key = "exampleobject"; //对象在存储桶中的位置,即称对象键.
    DeleteObjectRequest request = new DeleteObjectRequest(bucket, key);
    //设置签名有效时长
    request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
    //执行请求
    DeleteObjectResult result = cosXml.DeleteObject(request);
    //请求成功
    Console.WriteLine(result.GetResultInfo());
}
catch (COSXML.CosException.CosClientException clientEx)
{    
    //请求失败
    Console.WriteLine("CosClientException: " + clientEx.Message);
}
catch (COSXML.CosException.CosServerException serverEx)
{
    //请求失败
    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}