Search code examples
c#amazon-s3aws-sdk-net

AWS SDK S3 client not returning correct byte range


I want to stream a file with a certain starting position. I am able to do this using ordinary HTTP client given file URL in public S3 bucket.

Now, I want to use AWS SDK to do this. I use AWS SDK fro C# v3. My code is below:

    public Stream Stream Connect(long position){
        var s3Client = new AmazonS3Client();
        var request = new GetObjectRequest
        {
            BucketName = _bucketName,
            Key        = _path,
            ByteRange  = new ByteRange($"{position}-")
        };
        GetObjectResponse response = await s3Client.GetObjectAsync(request);
        return response.ResponseStream
    }

Apparently, I always get the byte starting from position 0 regardless position that I pass in the parameter.

Can anyone help me with this?


Solution

  • I'm not sure but according to the source code mentioned here you might try to change your code. It seems there is no validation towards the provided string for ByteRange class. This is what you might try:

        public Stream Stream Connect(long position){
            var s3Client = new AmazonS3Client();
            var request = new GetObjectRequest
            {
                BucketName = _bucketName,
                Key        = _path,
                ByteRange  = new ByteRange($"bytes={position}-")
            };
            GetObjectResponse response = await s3Client.GetObjectAsync(request);
            return response.ResponseStream
        }
    

    You can check the documentation about range header here.