Skip to content

.NET Core 3.1 / C# から AWS S3 Bucket を表示するサンプル

.NET Core 3.1 上の C# で AWS S3 Bucket を表示するサンプルを書いたのでメモしておきます。

S3 Bucket を一覧表示する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;

namespace AwsS3Sample01
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string accessKey = "ACCESSKEY";
            string secretKey = "SECRETKEY";

            var config = new AmazonS3Config() { ServiceURL = "https://s3.amazonaws.com" };
            var s3client = new AmazonS3Client(accessKey, secretKey, config);

            ListBucketsResponse response = await s3client.ListBucketsAsync();
            foreach (S3Bucket bucket in response.Buckets)
            { Console.WriteLine("{0}", bucket.BucketName); }
        }
    }
}

S3 Bucket の中身を表示する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;

namespace AwsS3Sample
{
    class Program
    {
        private const string bucketName = "BUCKET";
        private const string accessKey = "ACCESSKEY";
        private const string secretKey = "SECRETKEY";
        private static IAmazonS3 s3client;

        static void Main(string[] args)
        {
            var config = new AmazonS3Config() { ServiceURL = "https://s3.amazonaws.com" };
            s3client = new AmazonS3Client(accessKey, secretKey, config);
            ListObjectAsync().Wait();
        }

        static async Task ListObjectAsync()
        {
            var request = new ListObjectsV2Request { BucketName = bucketName, MaxKeys = 10 };
            ListObjectsV2Response response;

            do
            {
                response = await s3client.ListObjectsV2Async(request);
                foreach (S3Object entry in response.S3Objects)
                {
                    Console.WriteLine("{0}", entry.Key);
                }
                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);
        }
    }
}