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

Raj
Raj
Member
496 Points
21 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: 4287
Total Answered: 2
Total Marked As Answer: 1
Posted On: 01-Aug-2022 23:07

Share:   fb twitter linkedin
Answers
Rashmi
Rashmi
Member
820 Points
17 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
thanks
 - Raj  14-Sep-2022 02:28
kikme
kikme
Member
210 Points
10 Posts
         

Thanks. Very helpful.

Posted On: 04-Oct-2023 02:33
 Log In to Chat