How to check if key exists in s3 bucket in c#?

Raj
Raj
Member
50 Points
15 Posts

I'm trying to check if a key exists in a given bucket in c#. I looked at the API but there aren't any methods that are useful. I tried to use getObject but it threw an exception. Is there a way to so?

Views: 38
Total Answered: 1
Total Marked As Answer: 0
Posted On: 01-Aug-2022 23:07

Share:   fb twitter linkedin
Answers
Rashmi
Rashmi
Member
184 Points
37 Posts
         

Try following method:

private async Task<bool> IsS3FileExists(string bucketName, string fileName, string versionId)
        {
            try
            {
                var s3Client = new AmazonS3Client();
                var request = new GetObjectMetadataRequest()
                {
                    BucketName = bucketName,
                    Key = fileName,
                    VersionId = !string.IsNullOrEmpty(versionId) ? versionId : null
                };

                var response = await s3Client.GetObjectMetadataAsync(request);

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"IsFileExists: Error during checking if file exists in s3 bucket: {JsonConvert.SerializeObject(ex)}");
                return false;
            }
        }

Use something like:

var isExists = await IsS3FileExists("mybucketName", "mydirectory/myfile.json", "");
Posted On: 08-Aug-2022 03:56
 Log In to Chat