8

I am trying to download a file from S3 to a byte array iin .net using c#.

I am following the below method:

var client = new AmazonS3Client(AccessKey, SecretKey, Amazon.RegionEndpoint.EUWEST2);
    using (client)
    {
        MemoryStream ms = new MemoryStream();
        GetObjectRequest getObjectRequest = new GetObjectRequest();
        getObjectRequest.BucketName = Bucketname;
        getObjectRequest.Key = Keyname;

        using (var getObjectResponse = client.GetObject(getObjectRequest))
        {
            getObjectResponse.ResponseStream.CopyTo(ms);
        }
 }
 

I referred to a stackoverflow answer and followed the above method.

However I am getting the following error saying;

GetObject is inaccessible due to protection level.

I am just learning S3, I am now confused if this error is because of bucket policy or class scope.

peterh
  • 11,875
  • 18
  • 85
  • 108
  • 3
    Possible duplicate of [Public class is inaccessible due to its protection level](https://stackoverflow.com/questions/18404264/public-class-is-inaccessible-due-to-its-protection-level) – vahdet Nov 26 '18 at 11:01
  • 1
    @vahdet - not a duplicate of the question you linked – Joe Nov 26 '18 at 12:28

1 Answers1

22

You mention .NET Core: most of the AWS APIs for .Net Core and .NET Standard only provide Async variants. You should use GetObjectAsync.

It's surprising that Amazon introduced this incompatibility as it would have been easy to provide a synchronous version, using code something like:

var task = s3Client.GetObjectAsync(request);
task.Wait();
return task.Result;
Joe
  • 122,218
  • 32
  • 205
  • 338
  • 3
    Thanks a ton! Would have taken hours to figure this out:) – Abhilash Gopalakrishna Nov 26 '18 at 12:41
  • @Joe just out of curiosity. do we really need that task.Wait()? Is this any different than using .Result at the end of s3Client.GetObjectAsync(request); ? isn't it going to run it syncronously anyways? – curiousBoy Feb 13 '23 at 11:24
  • 1
    @curiousBoy - no we don't. In fact, it might be better to call `GetAwaiter().GetResult` which has the advantage that it will propagate the original exception rather than wrapping it in an AggregateException, thus being "more compatible" with the synchronous GetObject method – Joe Feb 13 '23 at 18:40