らくがきちょう

なんとなく ~所属組織/団体とは無関係であり、個人の見解です~

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

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

S3 Bucket を一覧表示する

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 の中身を表示する

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);
        }
    }
}