c# 冷儲存示例

三木發表於2019-02-16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;

namespace ConsoleApplication2
{
    class Program
    {
        private static string s3Endpoint = "https://cn-north-1-s3.qiniu.com";
        private static string s3Region = "cn-north-1";
        private static string s3AccessKeyId = "ak";
        private static string s3AccessKeySecret = "sk";
        private static string s3BucketName = "huabei";//新建的華北機房空間
        private static string s3KeyName = "putty.exe";
        private static string filePath = "D:\tools\putty.exe";//D:	ools
        static void Main(string[] args)
        {
            AmazonS3Config s3Config = new AmazonS3Config
            {
                ServiceURL = s3Endpoint,
                AuthenticationRegion = s3Region,
                ForcePathStyle = true,
                SignatureVersion = "v4",
                SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256
            };

            var s3Client = new AmazonS3Client(s3AccessKeyId, s3AccessKeySecret, s3Config);

            putObject(client: s3Client);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }

        static void putObject(AmazonS3Client client)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = s3BucketName,
                    Key = s3KeyName,
                    FilePath = filePath
                };

                PutObjectResponse response = client.PutObject(request);

                Console.WriteLine("Put Object => ETag: {0}", response.ETag);
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine("Put Object => Code: {0}, Error: {1}", s3Exception.ErrorCode, s3Exception.Message);

                throw;
            }
            catch (AmazonClientException s3ClientException)
            {
                // 由於七牛雲端儲存上傳物件 (Object) 請求中響應頭 *ETag* 的演算法與 AWS S3 服務不同,應用開發者需要忽略該異常。
                if (s3ClientException.Message.Contains("Expected hash not equal to calculated hash"))
                {
                    Console.WriteLine("Ignore object hash checksum since algorithm of ETag in Qiniu Storage is different from AWS S3.");
                }
                else
                {
                    Console.WriteLine("Put Object => Error: {0}", s3ClientException.ToString());

                    throw;
                }
            }
        }

    }
}

相關文章