human: 如何处理七牛云的对象存储AWS SDK for .NET

gpt: [对象存储](https://developer.qiniu.com/kodo) > 使用指南 >
[开发指南](https://developer.qiniu.com/kodo/development_guidelines/8596/development-
guidelines) > [AWS S3
兼容](https://developer.qiniu.com/kodo/development_guidelines/4086/aws-s3-compatible)
> [兼容 SDK 示例](https://developer.qiniu.com/kodo/development_guidelines/12553/S3
SDK sample) > AWS SDK for .NET

#  AWS SDK for .NET

最近更新时间: 2024-02-19 17:11:27

# 导入 AWS SDK for .NET

确保 Microsoft .NET Core SDK, version 2.1, 3.1 或更新版本已经安装，包含 .NET 命令行工具以及 .NET
Core 运行时。

执行以下命令创建 .NET 项目

    
    
    dotnet new console --name S3QiniuExamples
    

然后添加 AWS SDK for .NET 包

    
    
    dotnet add S3QiniuExamples package AWSSDK.S3 --version 3.7.305.22
    dotnet add S3QiniuExamples package AWSSDK.SecurityToken --version 3.7.300.47
    

对于之后的每个代码示例，将代码创建在 `Program.cs` 后，执行

    
    
    dotnet run --project S3QiniuExamples
    

即可执行代码。

# 对象上传

## 获取客户端上传 URL

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new GetPreSignedUrlRequest
                {
                    BucketName = "<Bucket>",
                    Key = "<Key>",
                    Verb = HttpVerb.PUT,
                    Expires = DateTime.Now.AddSeconds(3600) // 有效期为一小时
                };
                var url = s3Client.GetPreSignedURL(request);
                Console.WriteLine("{0}", url);
            }
        }
    }
    

这段代码将生成一个经过预先签名的客户端上传 URL，有效期为一小时，客户端可以在过期时间内对该 URL 发送 HTTP PUT 请求将文件上传。

以下是用 curl 上传文件的案例：

    
    
    curl -X PUT --upload-file "<path/to/file>" "<presigned url>"
    

## 服务器端直传

### 单请求上传（文件）

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var putRequest = new PutObjectRequest
                {
                    BucketName = "<Bucket>",
                    Key = "<Key>",
                    FilePath = "<path/to/upload>"
                };
    
                try
                {
                    var result = await s3Client.PutObjectAsync(putRequest);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("ETag: {0}", result.ETag);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

### 单请求上传（数据流）

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                using (var fileStream = new FileStream("<path/to/upload>", FileMode.Open))
                {
                    var putRequest = new PutObjectRequest
                    {
                        BucketName = "<Bucket>",
                        Key = "<Key>",
                        InputStream = fileStream,
                    };
    
                    try
                    {
                        var result = await s3Client.PutObjectAsync(putRequest);
                        if (result.HttpStatusCode == HttpStatusCode.OK)
                        {
                            Console.WriteLine("ETag: {0}", result.ETag);
                        }
                        else
                        {
                            Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                        }
                    }
                    catch (AmazonS3Exception ex)
                    {
                        Console.WriteLine(ex);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        throw;
                    }
                }
            }
        }
    }
    

### 分片上传（文件）

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                const string LOCAL_FILE_PATH = "<path/to/upload>";
                try
                {
                    long totalFileSize = new FileInfo(LOCAL_FILE_PATH).Length;
                    long uploadedSize = 0;
    
                    var initiateMultipartUploadRequest = new InitiateMultipartUploadRequest
                    {
                        BucketName = "<Bucket>",
                        Key = "<Key>",
                    };
                    var initiateMultipartUploadResponse = await s3Client.InitiateMultipartUploadAsync(initiateMultipartUploadRequest);
    
                    const long PART_SIZE = 5 * 1024 * 1024; // 分片大小为 5 MB
                    var partCount = (int)Math.Ceiling((double)totalFileSize / PART_SIZE);
                    var completeMultipartUploadRequest = new CompleteMultipartUploadRequest
                    {
                        BucketName = initiateMultipartUploadRequest.BucketName,
                        Key = initiateMultipartUploadRequest.Key,
                        UploadId = initiateMultipartUploadResponse.UploadId
                    };
    
                    // 这里给出的案例是串行分片上传。可以自行改造成并行分片上传以进一步提升上传速度
                    for (var i = 0; i < partCount; i++)
                    {
                        var uploadPartRequest = new UploadPartRequest
                        {
                            BucketName = initiateMultipartUploadRequest.BucketName,
                            Key = initiateMultipartUploadRequest.Key,
                            UploadId = initiateMultipartUploadResponse.UploadId,
                            PartNumber = i + 1,
                            PartSize = Math.Min(PART_SIZE, totalFileSize - uploadedSize),
                            FilePath = LOCAL_FILE_PATH,
                            FilePosition = uploadedSize
                        };
                        var uploadPartResponse = await s3Client.UploadPartAsync(uploadPartRequest);
                        completeMultipartUploadRequest.AddPartETags(uploadPartResponse);
                        uploadedSize += uploadPartRequest.PartSize;
                    }
    
                    var completeMultipartUploadResponse = await s3Client.CompleteMultipartUploadAsync(completeMultipartUploadRequest);
                    if (completeMultipartUploadResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("ETag: {0}", completeMultipartUploadResponse.ETag);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", completeMultipartUploadResponse.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

### 上传文件

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Transfer;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var transferUtility = new TransferUtility(s3Client);
                    await transferUtility.UploadAsync("<path/to/upload>", "<Bucket>", "<Key>");
                    Console.WriteLine("Done");
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

### 上传目录

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Transfer;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var transferUtility = new TransferUtility(s3Client);
                    await transferUtility.UploadDirectoryAsync("<path/to/upload>", "<Bucket>");
                    Console.WriteLine("Done");
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

# 对象下载

## 获取客户端下载 URL

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new GetPreSignedUrlRequest
                {
                    BucketName = "<Bucket>",
                    Key = "<Key>",
                    Verb = HttpVerb.GET,
                    Expires = DateTime.Now.AddSeconds(3600) // 有效期为一小时
                };
                var url = s3Client.GetPreSignedURL(request);
                Console.WriteLine("{0}", url);
            }
        }
    }
    

这段代码将生成一个经过预先签名的客户端下载 URL，有效期为一小时，客户端可以在过期时间内对该 URL 发送 HTTP GET 请求将文件下载。

以下是用 curl 下载文件的案例：

    
    
    curl -o "<path/to/download>" "<presigned url>"
    

## 服务器端直接下载

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new GetObjectRequest
                {
                    BucketName = "<Bucket>",
                    Key = "<Key>"
                };
                try
                {
                    using (var response = await s3Client.GetObjectAsync(request))
                    {
                        if (response.HttpStatusCode == HttpStatusCode.OK)
                        {
                            using (var responseStream = response.ResponseStream)
                            using (var fileStream = new FileStream("<path/to/download>", FileMode.OpenOrCreate))
                            {
                                await responseStream.CopyToAsync(fileStream);
                            }
                            Console.WriteLine("Done");
                        }
                        else
                        {
                            Console.WriteLine("Unexpected Status Code: {0}", response.HttpStatusCode);
                        }
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 下载文件

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Transfer;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var transferUtility = new TransferUtility(s3Client);
                    await transferUtility.DownloadAsync("<path/to/download>", "<Bucket>", "<Key>");
                    Console.WriteLine("Done");
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 下载目录

创建 `Program.cs`

    
    
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Transfer;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var transferUtility = new TransferUtility(s3Client);
                    await transferUtility.DownloadDirectoryAsync("<Bucket>", "<RemoteDirectoryPath>", "<LocalDirectoryPath>");
                    Console.WriteLine("Done");
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

# 对象管理

## 获取对象信息

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var result = await s3Client.GetObjectMetadataAsync(bucketName: "<Bucket>", key: "<Key>");
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("ETag: {0}", result.ETag);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 修改对象 MimeType

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new CopyObjectRequest
                {
                    SourceBucket = "<Bucket>",
                    SourceKey = "<Key>",
                    DestinationBucket = "<Bucket>",
                    DestinationKey = "<Key>",
                    ContentType = "<NewContentType>",
                    MetadataDirective = S3MetadataDirective.REPLACE
                };
                try
                {
                    var result = await s3Client.CopyObjectAsync(request);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("Done");
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 修改对象存储类型

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new CopyObjectRequest
                {
                    SourceBucket = "<Bucket>",
                    SourceKey = "<Key>",
                    DestinationBucket = "<Bucket>",
                    DestinationKey = "<Key>",
                    StorageClass = S3StorageClass.Glacier,
                    MetadataDirective = S3MetadataDirective.REPLACE
                };
                try
                {
                    var result = await s3Client.CopyObjectAsync(request);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("Done");
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 复制对象副本

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                var request = new CopyObjectRequest
                {
                    SourceBucket = "<Bucket>",
                    SourceKey = "<Key>",
                    DestinationBucket = "<Bucket>",
                    DestinationKey = "<Key>",
                    MetadataDirective = S3MetadataDirective.COPY
                };
                try
                {
                    var result = await s3Client.CopyObjectAsync(request);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("Done");
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 复制对象副本（大于 5GB）

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var headObjectRequest = new GetObjectMetadataRequest
                    {
                        BucketName = "<FromBucket>",
                        Key = "<FromKey>"
                    };
                    var headObjectResponse = await s3Client.GetObjectMetadataAsync(headObjectRequest);
                    if (headObjectResponse.HttpStatusCode != HttpStatusCode.OK)
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", headObjectResponse.HttpStatusCode);
                        return;
                    }
    
                    var createMultipartUploadRequest = await s3Client.InitiateMultipartUploadAsync(bucketName: "<ToBucket>", key: "<ToKey>");
                    if (createMultipartUploadRequest.HttpStatusCode != HttpStatusCode.OK)
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", createMultipartUploadRequest.HttpStatusCode);
                        return;
                    }
    
                    const long PART_SIZE = 5 * 1024 * 1024; // 分片大小，调整过小会影响复制速度，调整过大可能导致服务器超时
                    long partSize = PART_SIZE;
                    List<PartETag> partETags = new List<PartETag>();
                    // 这里给出的案例是串行分片复制。可以自行改造成并行分片复制以进一步提升复制速度
                    for (long copied = 0, partNumber = 1; copied < headObjectResponse.ContentLength; copied += partSize, partNumber++)
                    {
                        partSize = Math.Min(headObjectResponse.ContentLength - copied, PART_SIZE);
                        var uploadPartCopyRequest = new CopyPartRequest
                        {
                            DestinationBucket = createMultipartUploadRequest.BucketName,
                            DestinationKey = createMultipartUploadRequest.Key,
                            SourceBucket = headObjectRequest.BucketName,
                            SourceKey = headObjectRequest.Key,
                            UploadId = createMultipartUploadRequest.UploadId,
                            PartNumber = (int)partNumber,
                            FirstByte = copied,
                            LastByte = copied + partSize,
                        };
                        var uploadPartCopyResponse = await s3Client.CopyPartAsync(uploadPartCopyRequest);
                        if (uploadPartCopyResponse.HttpStatusCode != HttpStatusCode.OK)
                        {
                            Console.WriteLine("Unexpected Status Code: {0}", uploadPartCopyResponse.HttpStatusCode);
                            return;
                        }
                        partETags.Add(new PartETag
                        {
                            PartNumber = uploadPartCopyRequest.PartNumber,
                            ETag = uploadPartCopyResponse.ETag,
                        });
                        Console.WriteLine("PartNumber: {0}", uploadPartCopyRequest.PartNumber);
                    }
                    var completeMultipartUploadRequest = new CompleteMultipartUploadRequest
                    {
                        BucketName = createMultipartUploadRequest.BucketName,
                        Key = createMultipartUploadRequest.Key,
                        UploadId = createMultipartUploadRequest.UploadId,
                        PartETags = partETags,
                    };
                    var completeMultipartUploadAsync = await s3Client.CompleteMultipartUploadAsync(completeMultipartUploadRequest);
                    if (completeMultipartUploadAsync.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("ETag: {0}", completeMultipartUploadAsync.ETag);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", completeMultipartUploadAsync.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
    
            }
        }
    }
    

## 删除空间中的文件

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var deleteObjectRequest = new DeleteObjectRequest
                    {
                        BucketName = "<BucketName>",
                        Key = "<Key>"
                    };
                    var deleteObjectResponse = await s3Client.DeleteObjectAsync(deleteObjectRequest);
                    if (deleteObjectResponse.HttpStatusCode == HttpStatusCode.NoContent)
                    {
                        Console.WriteLine("Done");
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", deleteObjectResponse.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 获取指定前缀的文件列表

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var request = new ListObjectsV2Request
                    {
                        BucketName = "<Bucket>",
                        Prefix = "<KeyPrefix>",
                    };
                    var result = await s3Client.ListObjectsV2Async(request);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        foreach (var obj in result.S3Objects)
                        {
                            Console.WriteLine("Key: {0}", obj.Key);
                            Console.WriteLine("ETag: {0}", obj.ETag);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

## 批量删除空间中的文件

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(credentials, s3Config);
    
                try
                {
                    var objectsToDelete = new List<KeyVersion> { new() { Key = "<Key1>" }, new() { Key = "<Key2>" } };
                    var request = new DeleteObjectsRequest
                    {
                        BucketName = "<Bucket>",
                        Objects = objectsToDelete
                    };
                    var result = await s3Client.DeleteObjectsAsync(request);
                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("Done");
                    }
                    else
                    {
                        Console.WriteLine("Unexpected Status Code: {0}", result.HttpStatusCode);
                    }
                }
                catch (AmazonS3Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }
        }
    }
    

# 临时安全凭证

创建 `Program.cs`

    
    
    using System.Net;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.SecurityToken;
    using Amazon.SecurityToken.Model;
    
    namespace S3QiniuExamples
    {
        class Program
        {
            class STSCredentials : RefreshingAWSCredentials
            {
                private AmazonSecurityTokenServiceClient stsClient;
    
                public STSCredentials(AWSCredentials credentials, AmazonSecurityTokenServiceConfig stsConfig)
                {
                    stsClient = new AmazonSecurityTokenServiceClient(credentials, stsConfig);
                }
    
                protected override CredentialsRefreshState GenerateNewCredentials()
                {
                    var getFederationTokenRequest = new GetFederationTokenRequest();
                    getFederationTokenRequest.Name = "Bob";
                    getFederationTokenRequest.DurationSeconds = 3600;
                    getFederationTokenRequest.Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":[\"*\"],\"Resource\":[\"*\"]}]}";
                    var getFederationTokenTask = Task.Run(async () => await stsClient.GetFederationTokenAsync(getFederationTokenRequest));
                    getFederationTokenTask.Wait();
                    var getFederationTokenResponse = getFederationTokenTask.Result;
                    if (getFederationTokenResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        var credentials = new ImmutableCredentials(getFederationTokenResponse.Credentials.AccessKeyId, getFederationTokenResponse.Credentials.SecretAccessKey, getFederationTokenResponse.Credentials.SessionToken);
                        var expiration = getFederationTokenResponse.Credentials.Expiration;
                        return new CredentialsRefreshState(credentials, expiration);
                    }
                    else
                    {
                        throw new AmazonS3Exception(getFederationTokenResponse.ToString());
                    }
                }
            }
    
            static async Task Main(string[] args)
            {
                var credentials = new BasicAWSCredentials("<AccessKey>", "<SecretKey>");
                var stsConfig = new AmazonSecurityTokenServiceConfig
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var stsCredentials = new STSCredentials(credentials, stsConfig);
    
                var s3Config = new AmazonS3Config
                {
                    ServiceURL = "https://s3.cn-east-1.qiniucs.com"               // 华东-浙江区 endpoint
                };
                var s3Client = new AmazonS3Client(stsCredentials, s3Config);
    
                // 可以使用这些临时凭证调用 S3 服务
                var listBucketsResponse = await s3Client.ListBucketsAsync();
                if (listBucketsResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    foreach (var bucket in listBucketsResponse.Buckets)
                    {
                        Console.WriteLine(bucket.BucketName);
                    }
                }
                else
                {
                    Console.WriteLine("Unexpected Status Code: {0}", listBucketsResponse.HttpStatusCode);
                }
            }
        }
    }
    

以上内容是否对您有帮助？