Home > Blockchain >  How to reference AWS S3 Bucket and its contents in C#
How to reference AWS S3 Bucket and its contents in C#

Time:11-07

I am creating a visual studio project with the AWSSDK.S3 Nuget and trying to create a program with the goal of listing contents of a specific S3 bucket. The specific bucket goes by the name "testbucktest" and has jpg files within it. So far, I have been able to list the all of the buckets, but am struggling with actually referencing the bucket itself. How would I go about referencing the bucket, then listing its content?

This is a secondary question, but I also want to eventually reference the specific contents of the bucket. If I have the name of the file, how would I go about doing that?

This is what I have done so far. I have been able to list the buckets into a textbox by pressing a button:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Amazon.S3;
using Amazon.S3.Model;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var Client = new AmazonS3Client();
            var ListRe = await MyAsync(Client);
            foreach (S3Bucket a in ListRe.Buckets)
            {
                textBox1.Text  = a.BucketName   ", ";
            }
        }

        private static async Task<ListBucketsResponse> MyAsync(IAmazonS3 Client)
        {
            return await Client.ListBucketsAsync();
        }
    }
}

I have tried listing the actual bucket itself ("testbuckettest"), but have been unable to without error. Would someone be able to assist?

CodePudding user response:

You can get a list of buckets by doing ListBucketsAsync

You can use the BucketName from the bucket to list the objects within that bucket by using ListObjectsV2Async

You can get a specific object (and it's contents) by its Key which is like their path by using GetObjectAsync

using (var s3 = new AmazonS3Client())
{
    var buckets = await s3.ListBucketsAsync();

    var firstBucketName = buckets.Buckets.First();

    var firstBucketObjects = await s3.ListObjectsV2Async(new ListObjectsV2Request
    {
        BucketName = firstBucketName
    });

    var firstBucketFirstObjectKey = firstBucketObjects.S3Objects.First().Key;

    var firstBucketFirstObject = await s3.GetObjectAsync(new GetObjectRequest
    {
        BucketName = firstBucket.BucketName,
        Key = firstBucketFirstObjectKey
    });
}
  • Related