Check if a folder exists in S3 through C#


To check if a folder exists in a bucket is one of the basic requirements in any application which uses S3 buckets. I have demonstrated a small function in this blog, which checks if a given folder exists in S3.

This function takes ‘Key’ as input. ‘Key’ here is the folder path in string format, excluding the bucket name. This function returns a bool value.

You can just pass the key(For example if ‘Test’ is an S3 bucket and there is a folder ‘InTest’ in the bucket, if you have to check if ‘InTest’ exists, the key is just ‘InTest’) to the function and it returns true if the key exists else returns false. Specify the ‘AwsAccessKey’, ‘AwsSecretAccessKey’ and the ‘BucketName’ in the appropriate places in the function below.

To implement this function, you have to install a NuGet package called AWSSDK.S3

using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;

namespace CheckS3
{
    public static class S3Utility
    {
        public static async Task<bool> DoesFolderexists(string Key)
        {
            ListObjectsResponse response = null;
            try
            {
                using (AmazonS3Client client = new AmazonS3Client("<AwsAccessKey>", "<AwsSecretAccessKey>", Amazon.RegionEndpoint.USEast1))
                {
                    ListObjectsRequest request = new ListObjectsRequest
                    {
                        Bucket Name = "<bucket-name>",
                        Prefix = Key
                    };
                    response = await client.ListObjectsAsync(request);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return (response != null && response.S3Objects != null && response.S3Objects.Count > 0);
        }
    }
}

Leave A Comment

Your email address will not be published. Required fields are marked *