快速入门

最近更新时间: 2024-10-17 17:10:00

下载与安装

相关资源

环境依赖

COS XML .NET SDK 基于 .NET Standard 2.0 开发。

  • Windows:安装 .NET Core 2.0 及以上版本,或者 .NET Framework 4.6.1 及以上版本。

  • 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

您也可以在 这里 手动下载我们的SDK。

其他依赖

我们使用了 Newtonsoft.Json 作为第三方依赖,如果您本地没有自动拉取,可以在 csproj 文件里手动添加:

<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />

开始使用

下面为您介绍如何使用 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 region = "ap-beijing"; //设置一个默认的存储桶地域
string domain = "DOMAIN.com";   // 替换成用户的 Domain

string endpoint = String.format("cos.%s.%s", region, domain);

CosXmlConfig config = new CosXmlConfig.Builder()
    .setEndpointSuffix(endpoint)
    .SetConnectionTimeoutMs(60000)  //设置连接超时时间,单位 毫秒 ,默认 45000ms
    .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位 毫秒 ,默认 45000ms
    .IsHttps(true)  //设置默认 https 请求
    .SetRegion(region)  //设置一个默认的存储桶地域
    .SetDebugLog(true)  //显示日志
    .Build();  //创建 CosXmlConfig 对象

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

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

//初始化 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());
}