4

I'm working on upgrading our software to target .NET Standard. I note that the AWS SDK does not support the AWS.S3.IO library, and therefore the S3FileInfo code we used previously needs to be updated.

One that jumps out is the Length and Exists methods. These used to do a HEAD request to S3 to determine what was required. I can't see an equivalent right now - and it looks as though I'll have to do a GetObjectRequest instead, which is a full GET request.

Is this correct, or is there a way to perform a HEAD operation to check for existence and length in the .NET Standard AWS SDK?

tapmantwo
  • 121
  • 2
  • 7

2 Answers2

4

Looks as though GetObjectMetadataAsync is the best alternative.

https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/MS3GetObjectMetadataAsyncStringStringCancellationToken.html

cbp
  • 25,252
  • 29
  • 125
  • 205
tapmantwo
  • 121
  • 2
  • 7
2

This AWS Forum post led me to the original code for S3FileInfo:

GitHub Link

I find that extremely useful for recreating the functionality in .Net Core 6 that I require, namely, does the file exist or not.

Here's what my code ended up being, based on that code:

public async Task<bool> fileExists(string bucket, string key)
{
    try
    {
      // you provide the s3Client in your call, or create a new one
      await s3Client.GetObjectMetadataAsync(bucket, key);

      return true;
    }
    catch (AmazonS3Exception ex)
    {
       if (string.Equals(ex.ErrorCode, "NotFound"))
           return false;

       throw;
     }
}

(yes, GetObjectMetadataAsync throws an exception if the key doesn't exist; reminds me of my Microsoft DAO days!)

Maybe someday Amazon will have a better SDK for .Net Core?

*** UPDATE Aug 2023 ***

A little over a year later, not much has changed. However these links may be helpful to future readers:

Requesting a way to check for existence without an exception

dlchambers example of how to call synchronously if necessary Beware of deadlocks!

Mmm
  • 682
  • 9
  • 11